@promptbook/ollama 0.94.0-1 → 0.94.0-3
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/README.md +6 -8
- package/esm/index.es.js +1768 -151
- package/esm/index.es.js.map +1 -1
- package/esm/typings/src/_packages/ollama.index.d.ts +4 -2
- package/esm/typings/src/execution/AvailableModel.d.ts +9 -1
- package/esm/typings/src/llm-providers/_common/filterModels.d.ts +2 -2
- package/esm/typings/src/llm-providers/anthropic-claude/AnthropicClaudeExecutionToolsOptions.d.ts +1 -1
- package/esm/typings/src/llm-providers/azure-openai/AzureOpenAiExecutionToolsOptions.d.ts +1 -1
- package/esm/typings/src/llm-providers/deepseek/DeepseekExecutionToolsOptions.d.ts +1 -1
- package/esm/typings/src/llm-providers/google/GoogleExecutionToolsOptions.d.ts +1 -1
- package/esm/typings/src/llm-providers/ollama/OllamaExecutionToolsOptions.d.ts +23 -12
- package/esm/typings/src/llm-providers/ollama/createOllamaExecutionTools.d.ts +3 -3
- package/esm/typings/src/llm-providers/openai/OpenAiAssistantExecutionToolsOptions.d.ts +1 -1
- package/esm/typings/src/llm-providers/openai/OpenAiExecutionTools.d.ts +1 -1
- package/esm/typings/src/llm-providers/openai/OpenAiExecutionToolsOptions.d.ts +1 -1
- package/esm/typings/src/llm-providers/openai/createOpenAiExecutionTools.d.ts +2 -0
- package/esm/typings/src/llm-providers/openai/openai-models.d.ts +1 -7
- package/esm/typings/src/version.d.ts +1 -1
- package/package.json +4 -2
- package/umd/index.umd.js +1773 -156
- package/umd/index.umd.js.map +1 -1
- package/esm/typings/src/llm-providers/ollama/OllamaExecutionTools.d.ts +0 -19
package/esm/index.es.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import Bottleneck from 'bottleneck';
|
|
2
|
-
import
|
|
3
|
-
import
|
|
2
|
+
import colors from 'colors';
|
|
3
|
+
import OpenAI from 'openai';
|
|
4
4
|
import spaceTrim, { spaceTrim as spaceTrim$1 } from 'spacetrim';
|
|
5
|
+
import { randomBytes } from 'crypto';
|
|
5
6
|
|
|
6
7
|
// ⚠️ WARNING: This code has been generated so that any manual changes will be overwritten
|
|
7
8
|
/**
|
|
@@ -17,12 +18,52 @@ const BOOK_LANGUAGE_VERSION = '1.0.0';
|
|
|
17
18
|
* @generated
|
|
18
19
|
* @see https://github.com/webgptorg/promptbook
|
|
19
20
|
*/
|
|
20
|
-
const PROMPTBOOK_ENGINE_VERSION = '0.94.0-
|
|
21
|
+
const PROMPTBOOK_ENGINE_VERSION = '0.94.0-3';
|
|
21
22
|
/**
|
|
22
23
|
* TODO: string_promptbook_version should be constrained to the all versions of Promptbook engine
|
|
23
24
|
* Note: [💞] Ignore a discrepancy between file name and entity name
|
|
24
25
|
*/
|
|
25
26
|
|
|
27
|
+
/**
|
|
28
|
+
* Detects if the code is running in a browser environment in main thread (Not in a web worker)
|
|
29
|
+
*
|
|
30
|
+
* Note: `$` is used to indicate that this function is not a pure function - it looks at the global object to determine the environment
|
|
31
|
+
*
|
|
32
|
+
* @public exported from `@promptbook/utils`
|
|
33
|
+
*/
|
|
34
|
+
const $isRunningInBrowser = new Function(`
|
|
35
|
+
try {
|
|
36
|
+
return this === window;
|
|
37
|
+
} catch (e) {
|
|
38
|
+
return false;
|
|
39
|
+
}
|
|
40
|
+
`);
|
|
41
|
+
/**
|
|
42
|
+
* TODO: [🎺]
|
|
43
|
+
*/
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Detects if the code is running in a web worker
|
|
47
|
+
*
|
|
48
|
+
* Note: `$` is used to indicate that this function is not a pure function - it looks at the global object to determine the environment
|
|
49
|
+
*
|
|
50
|
+
* @public exported from `@promptbook/utils`
|
|
51
|
+
*/
|
|
52
|
+
const $isRunningInWebWorker = new Function(`
|
|
53
|
+
try {
|
|
54
|
+
if (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope) {
|
|
55
|
+
return true;
|
|
56
|
+
} else {
|
|
57
|
+
return false;
|
|
58
|
+
}
|
|
59
|
+
} catch (e) {
|
|
60
|
+
return false;
|
|
61
|
+
}
|
|
62
|
+
`);
|
|
63
|
+
/**
|
|
64
|
+
* TODO: [🎺]
|
|
65
|
+
*/
|
|
66
|
+
|
|
26
67
|
/**
|
|
27
68
|
* Name for the Promptbook
|
|
28
69
|
*
|
|
@@ -43,6 +84,34 @@ const ADMIN_EMAIL = 'pavol@ptbk.io';
|
|
|
43
84
|
* @public exported from `@promptbook/core`
|
|
44
85
|
*/
|
|
45
86
|
const ADMIN_GITHUB_NAME = 'hejny';
|
|
87
|
+
// <- TODO: [🧠] Better system for generator warnings - not always "code" and "by `@promptbook/cli`"
|
|
88
|
+
/**
|
|
89
|
+
* The maximum number of iterations for a loops
|
|
90
|
+
*
|
|
91
|
+
* @private within the repository - too low-level in comparison with other `MAX_...`
|
|
92
|
+
*/
|
|
93
|
+
const LOOP_LIMIT = 1000;
|
|
94
|
+
/**
|
|
95
|
+
* Strings to represent various values in the context of parameter values
|
|
96
|
+
*
|
|
97
|
+
* @public exported from `@promptbook/utils`
|
|
98
|
+
*/
|
|
99
|
+
const VALUE_STRINGS = {
|
|
100
|
+
empty: '(nothing; empty string)',
|
|
101
|
+
null: '(no value; null)',
|
|
102
|
+
undefined: '(unknown value; undefined)',
|
|
103
|
+
nan: '(not a number; NaN)',
|
|
104
|
+
infinity: '(infinity; ∞)',
|
|
105
|
+
negativeInfinity: '(negative infinity; -∞)',
|
|
106
|
+
unserializable: '(unserializable value)',
|
|
107
|
+
circular: '(circular JSON)',
|
|
108
|
+
};
|
|
109
|
+
/**
|
|
110
|
+
* Small number limit
|
|
111
|
+
*
|
|
112
|
+
* @public exported from `@promptbook/utils`
|
|
113
|
+
*/
|
|
114
|
+
const SMALL_NUMBER = 0.001;
|
|
46
115
|
// <- TODO: [🧜♂️]
|
|
47
116
|
/**
|
|
48
117
|
* Default settings for parsing and generating CSV files in Promptbook.
|
|
@@ -68,40 +137,6 @@ const DEFAULT_MAX_REQUESTS_PER_MINUTE = 60;
|
|
|
68
137
|
* TODO: [🧠][🧜♂️] Maybe join remoteServerUrl and path into single value
|
|
69
138
|
*/
|
|
70
139
|
|
|
71
|
-
/**
|
|
72
|
-
* Generates random token
|
|
73
|
-
*
|
|
74
|
-
* Note: This function is cryptographically secure (it uses crypto.randomBytes internally)
|
|
75
|
-
*
|
|
76
|
-
* @private internal helper function
|
|
77
|
-
* @returns secure random token
|
|
78
|
-
*/
|
|
79
|
-
function $randomToken(randomness) {
|
|
80
|
-
return randomBytes(randomness).toString('hex');
|
|
81
|
-
}
|
|
82
|
-
/**
|
|
83
|
-
* TODO: Maybe use nanoid instead https://github.com/ai/nanoid
|
|
84
|
-
*/
|
|
85
|
-
|
|
86
|
-
/**
|
|
87
|
-
* This error indicates errors during the execution of the pipeline
|
|
88
|
-
*
|
|
89
|
-
* @public exported from `@promptbook/core`
|
|
90
|
-
*/
|
|
91
|
-
class PipelineExecutionError extends Error {
|
|
92
|
-
constructor(message) {
|
|
93
|
-
// Added id parameter
|
|
94
|
-
super(message);
|
|
95
|
-
this.name = 'PipelineExecutionError';
|
|
96
|
-
// TODO: [🐙] DRY - Maybe $randomId
|
|
97
|
-
this.id = `error-${$randomToken(8 /* <- TODO: To global config + Use Base58 to avoid similar char conflicts */)}`;
|
|
98
|
-
Object.setPrototypeOf(this, PipelineExecutionError.prototype);
|
|
99
|
-
}
|
|
100
|
-
}
|
|
101
|
-
/**
|
|
102
|
-
* TODO: [🧠][🌂] Add id to all errors
|
|
103
|
-
*/
|
|
104
|
-
|
|
105
140
|
/**
|
|
106
141
|
* Make error report URL for the given error
|
|
107
142
|
*
|
|
@@ -170,6 +205,88 @@ class UnexpectedError extends Error {
|
|
|
170
205
|
}
|
|
171
206
|
}
|
|
172
207
|
|
|
208
|
+
/**
|
|
209
|
+
* This error type indicates that somewhere in the code non-Error object was thrown and it was wrapped into the `WrappedError`
|
|
210
|
+
*
|
|
211
|
+
* @public exported from `@promptbook/core`
|
|
212
|
+
*/
|
|
213
|
+
class WrappedError extends Error {
|
|
214
|
+
constructor(whatWasThrown) {
|
|
215
|
+
const tag = `[🤮]`;
|
|
216
|
+
console.error(tag, whatWasThrown);
|
|
217
|
+
super(spaceTrim$1(`
|
|
218
|
+
Non-Error object was thrown
|
|
219
|
+
|
|
220
|
+
Note: Look for ${tag} in the console for more details
|
|
221
|
+
Please report issue on ${ADMIN_EMAIL}
|
|
222
|
+
`));
|
|
223
|
+
this.name = 'WrappedError';
|
|
224
|
+
Object.setPrototypeOf(this, WrappedError.prototype);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* Helper used in catch blocks to assert that the error is an instance of `Error`
|
|
230
|
+
*
|
|
231
|
+
* @param whatWasThrown Any object that was thrown
|
|
232
|
+
* @returns Nothing if the error is an instance of `Error`
|
|
233
|
+
* @throws `WrappedError` or `UnexpectedError` if the error is not standard
|
|
234
|
+
*
|
|
235
|
+
* @private within the repository
|
|
236
|
+
*/
|
|
237
|
+
function assertsError(whatWasThrown) {
|
|
238
|
+
// Case 1: Handle error which was rethrown as `WrappedError`
|
|
239
|
+
if (whatWasThrown instanceof WrappedError) {
|
|
240
|
+
const wrappedError = whatWasThrown;
|
|
241
|
+
throw wrappedError;
|
|
242
|
+
}
|
|
243
|
+
// Case 2: Handle unexpected errors
|
|
244
|
+
if (whatWasThrown instanceof UnexpectedError) {
|
|
245
|
+
const unexpectedError = whatWasThrown;
|
|
246
|
+
throw unexpectedError;
|
|
247
|
+
}
|
|
248
|
+
// Case 3: Handle standard errors - keep them up to consumer
|
|
249
|
+
if (whatWasThrown instanceof Error) {
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
// Case 4: Handle non-standard errors - wrap them into `WrappedError` and throw
|
|
253
|
+
throw new WrappedError(whatWasThrown);
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* Generates random token
|
|
258
|
+
*
|
|
259
|
+
* Note: This function is cryptographically secure (it uses crypto.randomBytes internally)
|
|
260
|
+
*
|
|
261
|
+
* @private internal helper function
|
|
262
|
+
* @returns secure random token
|
|
263
|
+
*/
|
|
264
|
+
function $randomToken(randomness) {
|
|
265
|
+
return randomBytes(randomness).toString('hex');
|
|
266
|
+
}
|
|
267
|
+
/**
|
|
268
|
+
* TODO: Maybe use nanoid instead https://github.com/ai/nanoid
|
|
269
|
+
*/
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* This error indicates errors during the execution of the pipeline
|
|
273
|
+
*
|
|
274
|
+
* @public exported from `@promptbook/core`
|
|
275
|
+
*/
|
|
276
|
+
class PipelineExecutionError extends Error {
|
|
277
|
+
constructor(message) {
|
|
278
|
+
// Added id parameter
|
|
279
|
+
super(message);
|
|
280
|
+
this.name = 'PipelineExecutionError';
|
|
281
|
+
// TODO: [🐙] DRY - Maybe $randomId
|
|
282
|
+
this.id = `error-${$randomToken(8 /* <- TODO: To global config + Use Base58 to avoid similar char conflicts */)}`;
|
|
283
|
+
Object.setPrototypeOf(this, PipelineExecutionError.prototype);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
/**
|
|
287
|
+
* TODO: [🧠][🌂] Add id to all errors
|
|
288
|
+
*/
|
|
289
|
+
|
|
173
290
|
/**
|
|
174
291
|
* Simple wrapper `new Date().toISOString()`
|
|
175
292
|
*
|
|
@@ -224,54 +341,6 @@ function $deepFreeze(objectValue) {
|
|
|
224
341
|
* TODO: [🧠] Is there a way how to meaningfully test this utility
|
|
225
342
|
*/
|
|
226
343
|
|
|
227
|
-
/**
|
|
228
|
-
* This error type indicates that somewhere in the code non-Error object was thrown and it was wrapped into the `WrappedError`
|
|
229
|
-
*
|
|
230
|
-
* @public exported from `@promptbook/core`
|
|
231
|
-
*/
|
|
232
|
-
class WrappedError extends Error {
|
|
233
|
-
constructor(whatWasThrown) {
|
|
234
|
-
const tag = `[🤮]`;
|
|
235
|
-
console.error(tag, whatWasThrown);
|
|
236
|
-
super(spaceTrim$1(`
|
|
237
|
-
Non-Error object was thrown
|
|
238
|
-
|
|
239
|
-
Note: Look for ${tag} in the console for more details
|
|
240
|
-
Please report issue on ${ADMIN_EMAIL}
|
|
241
|
-
`));
|
|
242
|
-
this.name = 'WrappedError';
|
|
243
|
-
Object.setPrototypeOf(this, WrappedError.prototype);
|
|
244
|
-
}
|
|
245
|
-
}
|
|
246
|
-
|
|
247
|
-
/**
|
|
248
|
-
* Helper used in catch blocks to assert that the error is an instance of `Error`
|
|
249
|
-
*
|
|
250
|
-
* @param whatWasThrown Any object that was thrown
|
|
251
|
-
* @returns Nothing if the error is an instance of `Error`
|
|
252
|
-
* @throws `WrappedError` or `UnexpectedError` if the error is not standard
|
|
253
|
-
*
|
|
254
|
-
* @private within the repository
|
|
255
|
-
*/
|
|
256
|
-
function assertsError(whatWasThrown) {
|
|
257
|
-
// Case 1: Handle error which was rethrown as `WrappedError`
|
|
258
|
-
if (whatWasThrown instanceof WrappedError) {
|
|
259
|
-
const wrappedError = whatWasThrown;
|
|
260
|
-
throw wrappedError;
|
|
261
|
-
}
|
|
262
|
-
// Case 2: Handle unexpected errors
|
|
263
|
-
if (whatWasThrown instanceof UnexpectedError) {
|
|
264
|
-
const unexpectedError = whatWasThrown;
|
|
265
|
-
throw unexpectedError;
|
|
266
|
-
}
|
|
267
|
-
// Case 3: Handle standard errors - keep them up to consumer
|
|
268
|
-
if (whatWasThrown instanceof Error) {
|
|
269
|
-
return;
|
|
270
|
-
}
|
|
271
|
-
// Case 4: Handle non-standard errors - wrap them into `WrappedError` and throw
|
|
272
|
-
throw new WrappedError(whatWasThrown);
|
|
273
|
-
}
|
|
274
|
-
|
|
275
344
|
/**
|
|
276
345
|
* Checks if the value is [🚉] serializable as JSON
|
|
277
346
|
* If not, throws an UnexpectedError with a rich error message and tracking
|
|
@@ -472,89 +541,1637 @@ function exportJson(options) {
|
|
|
472
541
|
*/
|
|
473
542
|
|
|
474
543
|
/**
|
|
475
|
-
*
|
|
544
|
+
* Nonce which is used for replacing things in strings
|
|
476
545
|
*
|
|
477
|
-
* @
|
|
546
|
+
* @private within the repository
|
|
478
547
|
*/
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
548
|
+
const REPLACING_NONCE = 'ptbkauk42kV2dzao34faw7FudQUHYPtW';
|
|
549
|
+
/**
|
|
550
|
+
* Nonce which is used as string which is not occurring in normal text
|
|
551
|
+
*
|
|
552
|
+
* @private within the repository
|
|
553
|
+
*/
|
|
554
|
+
const SALT_NONCE = 'ptbkghhewbvruets21t54et5';
|
|
555
|
+
/**
|
|
556
|
+
* Placeholder value indicating a parameter is missing its value.
|
|
557
|
+
*
|
|
558
|
+
* @private within the repository
|
|
559
|
+
*/
|
|
560
|
+
const RESERVED_PARAMETER_MISSING_VALUE = 'MISSING-' + REPLACING_NONCE;
|
|
561
|
+
/**
|
|
562
|
+
* Placeholder value indicating a parameter is restricted and cannot be used directly.
|
|
563
|
+
*
|
|
564
|
+
* @private within the repository
|
|
565
|
+
*/
|
|
566
|
+
const RESERVED_PARAMETER_RESTRICTED = 'RESTRICTED-' + REPLACING_NONCE;
|
|
567
|
+
/**
|
|
568
|
+
* The names of the parameters that are reserved for special purposes
|
|
569
|
+
*
|
|
570
|
+
* @public exported from `@promptbook/core`
|
|
571
|
+
*/
|
|
572
|
+
exportJson({
|
|
573
|
+
name: 'RESERVED_PARAMETER_NAMES',
|
|
574
|
+
message: `The names of the parameters that are reserved for special purposes`,
|
|
575
|
+
value: [
|
|
576
|
+
'content',
|
|
577
|
+
'context',
|
|
578
|
+
'knowledge',
|
|
579
|
+
'examples',
|
|
580
|
+
'modelName',
|
|
581
|
+
'currentDate',
|
|
582
|
+
// <- TODO: list here all command names
|
|
583
|
+
// <- TODO: Add more like 'date', 'modelName',...
|
|
584
|
+
// <- TODO: Add [emoji] + instructions ACRY when adding new reserved parameter
|
|
585
|
+
],
|
|
586
|
+
});
|
|
587
|
+
/**
|
|
588
|
+
* Note: [💞] Ignore a discrepancy between file name and entity name
|
|
589
|
+
*/
|
|
590
|
+
|
|
591
|
+
/**
|
|
592
|
+
* This error type indicates that some limit was reached
|
|
593
|
+
*
|
|
594
|
+
* @public exported from `@promptbook/core`
|
|
595
|
+
*/
|
|
596
|
+
class LimitReachedError extends Error {
|
|
597
|
+
constructor(message) {
|
|
598
|
+
super(message);
|
|
599
|
+
this.name = 'LimitReachedError';
|
|
600
|
+
Object.setPrototypeOf(this, LimitReachedError.prototype);
|
|
485
601
|
}
|
|
486
|
-
|
|
487
|
-
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
/**
|
|
605
|
+
* Format either small or big number
|
|
606
|
+
*
|
|
607
|
+
* @public exported from `@promptbook/utils`
|
|
608
|
+
*/
|
|
609
|
+
function numberToString(value) {
|
|
610
|
+
if (value === 0) {
|
|
611
|
+
return '0';
|
|
488
612
|
}
|
|
489
|
-
|
|
490
|
-
return
|
|
613
|
+
else if (Number.isNaN(value)) {
|
|
614
|
+
return VALUE_STRINGS.nan;
|
|
491
615
|
}
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
if (!res.ok)
|
|
495
|
-
throw new UnexpectedError(`Failed to reach Ollama API at ${this.options.baseUrl}`);
|
|
616
|
+
else if (value === Infinity) {
|
|
617
|
+
return VALUE_STRINGS.infinity;
|
|
496
618
|
}
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
if (!res.ok)
|
|
500
|
-
throw new UnexpectedError(`Error listing Ollama models: ${res.statusText}`);
|
|
501
|
-
const data = (await res.json());
|
|
502
|
-
return data.map((m) => ({ modelName: m.name, modelVariant: 'CHAT' }));
|
|
619
|
+
else if (value === -Infinity) {
|
|
620
|
+
return VALUE_STRINGS.negativeInfinity;
|
|
503
621
|
}
|
|
504
|
-
|
|
505
|
-
const
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
const modelName = modelRequirements.modelName || this.options.model;
|
|
510
|
-
const body = {
|
|
511
|
-
model: modelName,
|
|
512
|
-
messages: [
|
|
513
|
-
...(modelRequirements.systemMessage
|
|
514
|
-
? [{ role: 'system', content: modelRequirements.systemMessage }]
|
|
515
|
-
: []),
|
|
516
|
-
{ role: 'user', content: content },
|
|
517
|
-
],
|
|
518
|
-
parameters: parameters,
|
|
519
|
-
};
|
|
520
|
-
const start = $getCurrentDate();
|
|
521
|
-
const res = await this.limiter.schedule(() => fetch(`${this.options.baseUrl}/chat/completions`, {
|
|
522
|
-
method: 'POST',
|
|
523
|
-
headers: { 'Content-Type': 'application/json' },
|
|
524
|
-
body: JSON.stringify(body),
|
|
525
|
-
}));
|
|
526
|
-
if (!res.ok)
|
|
527
|
-
throw new PipelineExecutionError(`Ollama API error: ${res.statusText}`);
|
|
528
|
-
const json = await res.json();
|
|
529
|
-
const complete = $getCurrentDate();
|
|
530
|
-
if (!json.choices || !json.choices[0]) {
|
|
531
|
-
throw new PipelineExecutionError('No choices from Ollama');
|
|
622
|
+
for (let exponent = 0; exponent < 15; exponent++) {
|
|
623
|
+
const factor = 10 ** exponent;
|
|
624
|
+
const valueRounded = Math.round(value * factor) / factor;
|
|
625
|
+
if (Math.abs(value - valueRounded) / value < SMALL_NUMBER) {
|
|
626
|
+
return valueRounded.toFixed(exponent);
|
|
532
627
|
}
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
628
|
+
}
|
|
629
|
+
return value.toString();
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
/**
|
|
633
|
+
* Function `valueToString` will convert the given value to string
|
|
634
|
+
* This is useful and used in the `templateParameters` function
|
|
635
|
+
*
|
|
636
|
+
* Note: This function is not just calling `toString` method
|
|
637
|
+
* It's more complex and can handle this conversion specifically for LLM models
|
|
638
|
+
* See `VALUE_STRINGS`
|
|
639
|
+
*
|
|
640
|
+
* Note: There are 2 similar functions
|
|
641
|
+
* - `valueToString` converts value to string for LLM models as human-readable string
|
|
642
|
+
* - `asSerializable` converts value to string to preserve full information to be able to convert it back
|
|
643
|
+
*
|
|
644
|
+
* @public exported from `@promptbook/utils`
|
|
645
|
+
*/
|
|
646
|
+
function valueToString(value) {
|
|
647
|
+
try {
|
|
648
|
+
if (value === '') {
|
|
649
|
+
return VALUE_STRINGS.empty;
|
|
650
|
+
}
|
|
651
|
+
else if (value === null) {
|
|
652
|
+
return VALUE_STRINGS.null;
|
|
653
|
+
}
|
|
654
|
+
else if (value === undefined) {
|
|
655
|
+
return VALUE_STRINGS.undefined;
|
|
656
|
+
}
|
|
657
|
+
else if (typeof value === 'string') {
|
|
658
|
+
return value;
|
|
659
|
+
}
|
|
660
|
+
else if (typeof value === 'number') {
|
|
661
|
+
return numberToString(value);
|
|
662
|
+
}
|
|
663
|
+
else if (value instanceof Date) {
|
|
664
|
+
return value.toISOString();
|
|
665
|
+
}
|
|
666
|
+
else {
|
|
667
|
+
try {
|
|
668
|
+
return JSON.stringify(value);
|
|
669
|
+
}
|
|
670
|
+
catch (error) {
|
|
671
|
+
if (error instanceof TypeError && error.message.includes('circular structure')) {
|
|
672
|
+
return VALUE_STRINGS.circular;
|
|
673
|
+
}
|
|
674
|
+
throw error;
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
}
|
|
678
|
+
catch (error) {
|
|
679
|
+
assertsError(error);
|
|
680
|
+
console.error(error);
|
|
681
|
+
return VALUE_STRINGS.unserializable;
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
/**
|
|
686
|
+
* Replaces parameters in template with values from parameters object
|
|
687
|
+
*
|
|
688
|
+
* Note: This function is not places strings into string,
|
|
689
|
+
* It's more complex and can handle this operation specifically for LLM models
|
|
690
|
+
*
|
|
691
|
+
* @param template the template with parameters in {curly} braces
|
|
692
|
+
* @param parameters the object with parameters
|
|
693
|
+
* @returns the template with replaced parameters
|
|
694
|
+
* @throws {PipelineExecutionError} if parameter is not defined, not closed, or not opened
|
|
695
|
+
* @public exported from `@promptbook/utils`
|
|
696
|
+
*/
|
|
697
|
+
function templateParameters(template, parameters) {
|
|
698
|
+
for (const [parameterName, parameterValue] of Object.entries(parameters)) {
|
|
699
|
+
if (parameterValue === RESERVED_PARAMETER_MISSING_VALUE) {
|
|
700
|
+
throw new UnexpectedError(`Parameter \`{${parameterName}}\` has missing value`);
|
|
701
|
+
}
|
|
702
|
+
else if (parameterValue === RESERVED_PARAMETER_RESTRICTED) {
|
|
703
|
+
// TODO: [🍵]
|
|
704
|
+
throw new UnexpectedError(`Parameter \`{${parameterName}}\` is restricted to use`);
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
let replacedTemplates = template;
|
|
708
|
+
let match;
|
|
709
|
+
let loopLimit = LOOP_LIMIT;
|
|
710
|
+
while ((match = /^(?<precol>.*){(?<parameterName>\w+)}(.*)/m /* <- Not global */
|
|
711
|
+
.exec(replacedTemplates))) {
|
|
712
|
+
if (loopLimit-- < 0) {
|
|
713
|
+
throw new LimitReachedError('Loop limit reached during parameters replacement in `templateParameters`');
|
|
714
|
+
}
|
|
715
|
+
const precol = match.groups.precol;
|
|
716
|
+
const parameterName = match.groups.parameterName;
|
|
717
|
+
if (parameterName === '') {
|
|
718
|
+
// Note: Skip empty placeholders. It's used to avoid confusion with JSON-like strings
|
|
719
|
+
continue;
|
|
720
|
+
}
|
|
721
|
+
if (parameterName.indexOf('{') !== -1 || parameterName.indexOf('}') !== -1) {
|
|
722
|
+
throw new PipelineExecutionError('Parameter is already opened or not closed');
|
|
723
|
+
}
|
|
724
|
+
if (parameters[parameterName] === undefined) {
|
|
725
|
+
throw new PipelineExecutionError(`Parameter \`{${parameterName}}\` is not defined`);
|
|
726
|
+
}
|
|
727
|
+
let parameterValue = parameters[parameterName];
|
|
728
|
+
if (parameterValue === undefined) {
|
|
729
|
+
throw new PipelineExecutionError(`Parameter \`{${parameterName}}\` is not defined`);
|
|
730
|
+
}
|
|
731
|
+
parameterValue = valueToString(parameterValue);
|
|
732
|
+
// Escape curly braces in parameter values to prevent prompt-injection
|
|
733
|
+
parameterValue = parameterValue.replace(/[{}]/g, '\\$&');
|
|
734
|
+
if (parameterValue.includes('\n') && /^\s*\W{0,3}\s*$/.test(precol)) {
|
|
735
|
+
parameterValue = parameterValue
|
|
736
|
+
.split('\n')
|
|
737
|
+
.map((line, index) => (index === 0 ? line : `${precol}${line}`))
|
|
738
|
+
.join('\n');
|
|
739
|
+
}
|
|
740
|
+
replacedTemplates =
|
|
741
|
+
replacedTemplates.substring(0, match.index + precol.length) +
|
|
742
|
+
parameterValue +
|
|
743
|
+
replacedTemplates.substring(match.index + precol.length + parameterName.length + 2);
|
|
744
|
+
}
|
|
745
|
+
// [💫] Check if there are parameters that are not closed properly
|
|
746
|
+
if (/{\w+$/.test(replacedTemplates)) {
|
|
747
|
+
throw new PipelineExecutionError('Parameter is not closed');
|
|
748
|
+
}
|
|
749
|
+
// [💫] Check if there are parameters that are not opened properly
|
|
750
|
+
if (/^\w+}/.test(replacedTemplates)) {
|
|
751
|
+
throw new PipelineExecutionError('Parameter is not opened');
|
|
752
|
+
}
|
|
753
|
+
return replacedTemplates;
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
/**
|
|
757
|
+
* Counts number of characters in the text
|
|
758
|
+
*
|
|
759
|
+
* @public exported from `@promptbook/utils`
|
|
760
|
+
*/
|
|
761
|
+
function countCharacters(text) {
|
|
762
|
+
// Remove null characters
|
|
763
|
+
text = text.replace(/\0/g, '');
|
|
764
|
+
// Replace emojis (and also ZWJ sequence) with hyphens
|
|
765
|
+
text = text.replace(/(\p{Extended_Pictographic})\p{Modifier_Symbol}/gu, '$1');
|
|
766
|
+
text = text.replace(/(\p{Extended_Pictographic})[\u{FE00}-\u{FE0F}]/gu, '$1');
|
|
767
|
+
text = text.replace(/\p{Extended_Pictographic}(\u{200D}\p{Extended_Pictographic})*/gu, '-');
|
|
768
|
+
return text.length;
|
|
769
|
+
}
|
|
770
|
+
/**
|
|
771
|
+
* TODO: [🥴] Implement counting in formats - like JSON, CSV, XML,...
|
|
772
|
+
*/
|
|
773
|
+
|
|
774
|
+
/**
|
|
775
|
+
* Number of characters per standard line with 11pt Arial font size.
|
|
776
|
+
*
|
|
777
|
+
* @public exported from `@promptbook/utils`
|
|
778
|
+
*/
|
|
779
|
+
const CHARACTERS_PER_STANDARD_LINE = 63;
|
|
780
|
+
/**
|
|
781
|
+
* Number of lines per standard A4 page with 11pt Arial font size and standard margins and spacing.
|
|
782
|
+
*
|
|
783
|
+
* @public exported from `@promptbook/utils`
|
|
784
|
+
*/
|
|
785
|
+
const LINES_PER_STANDARD_PAGE = 44;
|
|
786
|
+
/**
|
|
787
|
+
* TODO: [🧠] Should be this `constants.ts` or `config.ts`?
|
|
788
|
+
* Note: [💞] Ignore a discrepancy between file name and entity name
|
|
789
|
+
*/
|
|
790
|
+
|
|
791
|
+
/**
|
|
792
|
+
* Counts number of lines in the text
|
|
793
|
+
*
|
|
794
|
+
* Note: This does not check only for the presence of newlines, but also for the length of the standard line.
|
|
795
|
+
*
|
|
796
|
+
* @public exported from `@promptbook/utils`
|
|
797
|
+
*/
|
|
798
|
+
function countLines(text) {
|
|
799
|
+
text = text.replace('\r\n', '\n');
|
|
800
|
+
text = text.replace('\r', '\n');
|
|
801
|
+
const lines = text.split('\n');
|
|
802
|
+
return lines.reduce((count, line) => count + Math.ceil(line.length / CHARACTERS_PER_STANDARD_LINE), 0);
|
|
803
|
+
}
|
|
804
|
+
/**
|
|
805
|
+
* TODO: [🥴] Implement counting in formats - like JSON, CSV, XML,...
|
|
806
|
+
*/
|
|
807
|
+
|
|
808
|
+
/**
|
|
809
|
+
* Counts number of pages in the text
|
|
810
|
+
*
|
|
811
|
+
* Note: This does not check only for the count of newlines, but also for the length of the standard line and length of the standard page.
|
|
812
|
+
*
|
|
813
|
+
* @public exported from `@promptbook/utils`
|
|
814
|
+
*/
|
|
815
|
+
function countPages(text) {
|
|
816
|
+
return Math.ceil(countLines(text) / LINES_PER_STANDARD_PAGE);
|
|
817
|
+
}
|
|
818
|
+
/**
|
|
819
|
+
* TODO: [🥴] Implement counting in formats - like JSON, CSV, XML,...
|
|
820
|
+
*/
|
|
821
|
+
|
|
822
|
+
/**
|
|
823
|
+
* Counts number of paragraphs in the text
|
|
824
|
+
*
|
|
825
|
+
* @public exported from `@promptbook/utils`
|
|
826
|
+
*/
|
|
827
|
+
function countParagraphs(text) {
|
|
828
|
+
return text.split(/\n\s*\n/).filter((paragraph) => paragraph.trim() !== '').length;
|
|
829
|
+
}
|
|
830
|
+
/**
|
|
831
|
+
* TODO: [🥴] Implement counting in formats - like JSON, CSV, XML,...
|
|
832
|
+
*/
|
|
833
|
+
|
|
834
|
+
/**
|
|
835
|
+
* Split text into sentences
|
|
836
|
+
*
|
|
837
|
+
* @public exported from `@promptbook/utils`
|
|
838
|
+
*/
|
|
839
|
+
function splitIntoSentences(text) {
|
|
840
|
+
return text.split(/[.!?]+/).filter((sentence) => sentence.trim() !== '');
|
|
841
|
+
}
|
|
842
|
+
/**
|
|
843
|
+
* Counts number of sentences in the text
|
|
844
|
+
*
|
|
845
|
+
* @public exported from `@promptbook/utils`
|
|
846
|
+
*/
|
|
847
|
+
function countSentences(text) {
|
|
848
|
+
return splitIntoSentences(text).length;
|
|
849
|
+
}
|
|
850
|
+
/**
|
|
851
|
+
* TODO: [🥴] Implement counting in formats - like JSON, CSV, XML,...
|
|
852
|
+
*/
|
|
853
|
+
|
|
854
|
+
const defaultDiacriticsRemovalMap = [
|
|
855
|
+
{
|
|
856
|
+
base: 'A',
|
|
857
|
+
letters: '\u0041\u24B6\uFF21\u00C0\u00C1\u00C2\u1EA6\u1EA4\u1EAA\u1EA8\u00C3\u0100\u0102\u1EB0\u1EAE\u1EB4\u1EB2\u0226\u01E0\u00C4\u01DE\u1EA2\u00C5\u01FA\u01CD\u0200\u0202\u1EA0\u1EAC\u1EB6\u1E00\u0104\u023A\u2C6F',
|
|
858
|
+
},
|
|
859
|
+
{ base: 'AA', letters: '\uA732' },
|
|
860
|
+
{ base: 'AE', letters: '\u00C6\u01FC\u01E2' },
|
|
861
|
+
{ base: 'AO', letters: '\uA734' },
|
|
862
|
+
{ base: 'AU', letters: '\uA736' },
|
|
863
|
+
{ base: 'AV', letters: '\uA738\uA73A' },
|
|
864
|
+
{ base: 'AY', letters: '\uA73C' },
|
|
865
|
+
{
|
|
866
|
+
base: 'B',
|
|
867
|
+
letters: '\u0042\u24B7\uFF22\u1E02\u1E04\u1E06\u0243\u0182\u0181',
|
|
868
|
+
},
|
|
869
|
+
{
|
|
870
|
+
base: 'C',
|
|
871
|
+
letters: '\u0043\u24B8\uFF23\u0106\u0108\u010A\u010C\u00C7\u1E08\u0187\u023B\uA73E',
|
|
872
|
+
},
|
|
873
|
+
{
|
|
874
|
+
base: 'D',
|
|
875
|
+
letters: '\u0044\u24B9\uFF24\u1E0A\u010E\u1E0C\u1E10\u1E12\u1E0E\u0110\u018B\u018A\u0189\uA779\u00D0',
|
|
876
|
+
},
|
|
877
|
+
{ base: 'DZ', letters: '\u01F1\u01C4' },
|
|
878
|
+
{ base: 'Dz', letters: '\u01F2\u01C5' },
|
|
879
|
+
{
|
|
880
|
+
base: 'E',
|
|
881
|
+
letters: '\u0045\u24BA\uFF25\u00C8\u00C9\u00CA\u1EC0\u1EBE\u1EC4\u1EC2\u1EBC\u0112\u1E14\u1E16\u0114\u0116\u00CB\u1EBA\u011A\u0204\u0206\u1EB8\u1EC6\u0228\u1E1C\u0118\u1E18\u1E1A\u0190\u018E',
|
|
882
|
+
},
|
|
883
|
+
{ base: 'F', letters: '\u0046\u24BB\uFF26\u1E1E\u0191\uA77B' },
|
|
884
|
+
{
|
|
885
|
+
base: 'G',
|
|
886
|
+
letters: '\u0047\u24BC\uFF27\u01F4\u011C\u1E20\u011E\u0120\u01E6\u0122\u01E4\u0193\uA7A0\uA77D\uA77E',
|
|
887
|
+
},
|
|
888
|
+
{
|
|
889
|
+
base: 'H',
|
|
890
|
+
letters: '\u0048\u24BD\uFF28\u0124\u1E22\u1E26\u021E\u1E24\u1E28\u1E2A\u0126\u2C67\u2C75\uA78D',
|
|
891
|
+
},
|
|
892
|
+
{
|
|
893
|
+
base: 'I',
|
|
894
|
+
letters: '\u0049\u24BE\uFF29\u00CC\u00CD\u00CE\u0128\u012A\u012C\u0130\u00CF\u1E2E\u1EC8\u01CF\u0208\u020A\u1ECA\u012E\u1E2C\u0197',
|
|
895
|
+
},
|
|
896
|
+
{ base: 'J', letters: '\u004A\u24BF\uFF2A\u0134\u0248' },
|
|
897
|
+
{
|
|
898
|
+
base: 'K',
|
|
899
|
+
letters: '\u004B\u24C0\uFF2B\u1E30\u01E8\u1E32\u0136\u1E34\u0198\u2C69\uA740\uA742\uA744\uA7A2',
|
|
900
|
+
},
|
|
901
|
+
{
|
|
902
|
+
base: 'L',
|
|
903
|
+
letters: '\u004C\u24C1\uFF2C\u013F\u0139\u013D\u1E36\u1E38\u013B\u1E3C\u1E3A\u0141\u023D\u2C62\u2C60\uA748\uA746\uA780',
|
|
904
|
+
},
|
|
905
|
+
{ base: 'LJ', letters: '\u01C7' },
|
|
906
|
+
{ base: 'Lj', letters: '\u01C8' },
|
|
907
|
+
{ base: 'M', letters: '\u004D\u24C2\uFF2D\u1E3E\u1E40\u1E42\u2C6E\u019C' },
|
|
908
|
+
{
|
|
909
|
+
base: 'N',
|
|
910
|
+
letters: '\u004E\u24C3\uFF2E\u01F8\u0143\u00D1\u1E44\u0147\u1E46\u0145\u1E4A\u1E48\u0220\u019D\uA790\uA7A4',
|
|
911
|
+
},
|
|
912
|
+
{ base: 'NJ', letters: '\u01CA' },
|
|
913
|
+
{ base: 'Nj', letters: '\u01CB' },
|
|
914
|
+
{
|
|
915
|
+
base: 'O',
|
|
916
|
+
letters: '\u004F\u24C4\uFF2F\u00D2\u00D3\u00D4\u1ED2\u1ED0\u1ED6\u1ED4\u00D5\u1E4C\u022C\u1E4E\u014C\u1E50\u1E52\u014E\u022E\u0230\u00D6\u022A\u1ECE\u0150\u01D1\u020C\u020E\u01A0\u1EDC\u1EDA\u1EE0\u1EDE\u1EE2\u1ECC\u1ED8\u01EA\u01EC\u00D8\u01FE\u0186\u019F\uA74A\uA74C',
|
|
917
|
+
},
|
|
918
|
+
{ base: 'OI', letters: '\u01A2' },
|
|
919
|
+
{ base: 'OO', letters: '\uA74E' },
|
|
920
|
+
{ base: 'OU', letters: '\u0222' },
|
|
921
|
+
{ base: 'OE', letters: '\u008C\u0152' },
|
|
922
|
+
{ base: 'oe', letters: '\u009C\u0153' },
|
|
923
|
+
{
|
|
924
|
+
base: 'P',
|
|
925
|
+
letters: '\u0050\u24C5\uFF30\u1E54\u1E56\u01A4\u2C63\uA750\uA752\uA754',
|
|
926
|
+
},
|
|
927
|
+
{ base: 'Q', letters: '\u0051\u24C6\uFF31\uA756\uA758\u024A' },
|
|
928
|
+
{
|
|
929
|
+
base: 'R',
|
|
930
|
+
letters: '\u0052\u24C7\uFF32\u0154\u1E58\u0158\u0210\u0212\u1E5A\u1E5C\u0156\u1E5E\u024C\u2C64\uA75A\uA7A6\uA782',
|
|
931
|
+
},
|
|
932
|
+
{
|
|
933
|
+
base: 'S',
|
|
934
|
+
letters: '\u0053\u24C8\uFF33\u1E9E\u015A\u1E64\u015C\u1E60\u0160\u1E66\u1E62\u1E68\u0218\u015E\u2C7E\uA7A8\uA784',
|
|
935
|
+
},
|
|
936
|
+
{
|
|
937
|
+
base: 'T',
|
|
938
|
+
letters: '\u0054\u24C9\uFF34\u1E6A\u0164\u1E6C\u021A\u0162\u1E70\u1E6E\u0166\u01AC\u01AE\u023E\uA786',
|
|
939
|
+
},
|
|
940
|
+
{ base: 'TZ', letters: '\uA728' },
|
|
941
|
+
{
|
|
942
|
+
base: 'U',
|
|
943
|
+
letters: '\u0055\u24CA\uFF35\u00D9\u00DA\u00DB\u0168\u1E78\u016A\u1E7A\u016C\u00DC\u01DB\u01D7\u01D5\u01D9\u1EE6\u016E\u0170\u01D3\u0214\u0216\u01AF\u1EEA\u1EE8\u1EEE\u1EEC\u1EF0\u1EE4\u1E72\u0172\u1E76\u1E74\u0244',
|
|
944
|
+
},
|
|
945
|
+
{ base: 'V', letters: '\u0056\u24CB\uFF36\u1E7C\u1E7E\u01B2\uA75E\u0245' },
|
|
946
|
+
{ base: 'VY', letters: '\uA760' },
|
|
947
|
+
{
|
|
948
|
+
base: 'W',
|
|
949
|
+
letters: '\u0057\u24CC\uFF37\u1E80\u1E82\u0174\u1E86\u1E84\u1E88\u2C72',
|
|
950
|
+
},
|
|
951
|
+
{ base: 'X', letters: '\u0058\u24CD\uFF38\u1E8A\u1E8C' },
|
|
952
|
+
{
|
|
953
|
+
base: 'Y',
|
|
954
|
+
letters: '\u0059\u24CE\uFF39\u1EF2\u00DD\u0176\u1EF8\u0232\u1E8E\u0178\u1EF6\u1EF4\u01B3\u024E\u1EFE',
|
|
955
|
+
},
|
|
956
|
+
{
|
|
957
|
+
base: 'Z',
|
|
958
|
+
letters: '\u005A\u24CF\uFF3A\u0179\u1E90\u017B\u017D\u1E92\u1E94\u01B5\u0224\u2C7F\u2C6B\uA762',
|
|
959
|
+
},
|
|
960
|
+
{
|
|
961
|
+
base: 'a',
|
|
962
|
+
letters: '\u0061\u24D0\uFF41\u1E9A\u00E0\u00E1\u00E2\u1EA7\u1EA5\u1EAB\u1EA9\u00E3\u0101\u0103\u1EB1\u1EAF\u1EB5\u1EB3\u0227\u01E1\u00E4\u01DF\u1EA3\u00E5\u01FB\u01CE\u0201\u0203\u1EA1\u1EAD\u1EB7\u1E01\u0105\u2C65\u0250',
|
|
963
|
+
},
|
|
964
|
+
{ base: 'aa', letters: '\uA733' },
|
|
965
|
+
{ base: 'ae', letters: '\u00E6\u01FD\u01E3' },
|
|
966
|
+
{ base: 'ao', letters: '\uA735' },
|
|
967
|
+
{ base: 'au', letters: '\uA737' },
|
|
968
|
+
{ base: 'av', letters: '\uA739\uA73B' },
|
|
969
|
+
{ base: 'ay', letters: '\uA73D' },
|
|
970
|
+
{
|
|
971
|
+
base: 'b',
|
|
972
|
+
letters: '\u0062\u24D1\uFF42\u1E03\u1E05\u1E07\u0180\u0183\u0253',
|
|
973
|
+
},
|
|
974
|
+
{
|
|
975
|
+
base: 'c',
|
|
976
|
+
letters: '\u0063\u24D2\uFF43\u0107\u0109\u010B\u010D\u00E7\u1E09\u0188\u023C\uA73F\u2184',
|
|
977
|
+
},
|
|
978
|
+
{
|
|
979
|
+
base: 'd',
|
|
980
|
+
letters: '\u0064\u24D3\uFF44\u1E0B\u010F\u1E0D\u1E11\u1E13\u1E0F\u0111\u018C\u0256\u0257\uA77A',
|
|
981
|
+
},
|
|
982
|
+
{ base: 'dz', letters: '\u01F3\u01C6' },
|
|
983
|
+
{
|
|
984
|
+
base: 'e',
|
|
985
|
+
letters: '\u0065\u24D4\uFF45\u00E8\u00E9\u00EA\u1EC1\u1EBF\u1EC5\u1EC3\u1EBD\u0113\u1E15\u1E17\u0115\u0117\u00EB\u1EBB\u011B\u0205\u0207\u1EB9\u1EC7\u0229\u1E1D\u0119\u1E19\u1E1B\u0247\u025B\u01DD',
|
|
986
|
+
},
|
|
987
|
+
{ base: 'f', letters: '\u0066\u24D5\uFF46\u1E1F\u0192\uA77C' },
|
|
988
|
+
{
|
|
989
|
+
base: 'g',
|
|
990
|
+
letters: '\u0067\u24D6\uFF47\u01F5\u011D\u1E21\u011F\u0121\u01E7\u0123\u01E5\u0260\uA7A1\u1D79\uA77F',
|
|
991
|
+
},
|
|
992
|
+
{
|
|
993
|
+
base: 'h',
|
|
994
|
+
letters: '\u0068\u24D7\uFF48\u0125\u1E23\u1E27\u021F\u1E25\u1E29\u1E2B\u1E96\u0127\u2C68\u2C76\u0265',
|
|
995
|
+
},
|
|
996
|
+
{ base: 'hv', letters: '\u0195' },
|
|
997
|
+
{
|
|
998
|
+
base: 'i',
|
|
999
|
+
letters: '\u0069\u24D8\uFF49\u00EC\u00ED\u00EE\u0129\u012B\u012D\u00EF\u1E2F\u1EC9\u01D0\u0209\u020B\u1ECB\u012F\u1E2D\u0268\u0131',
|
|
1000
|
+
},
|
|
1001
|
+
{ base: 'j', letters: '\u006A\u24D9\uFF4A\u0135\u01F0\u0249' },
|
|
1002
|
+
{
|
|
1003
|
+
base: 'k',
|
|
1004
|
+
letters: '\u006B\u24DA\uFF4B\u1E31\u01E9\u1E33\u0137\u1E35\u0199\u2C6A\uA741\uA743\uA745\uA7A3',
|
|
1005
|
+
},
|
|
1006
|
+
{
|
|
1007
|
+
base: 'l',
|
|
1008
|
+
letters: '\u006C\u24DB\uFF4C\u0140\u013A\u013E\u1E37\u1E39\u013C\u1E3D\u1E3B\u017F\u0142\u019A\u026B\u2C61\uA749\uA781\uA747',
|
|
1009
|
+
},
|
|
1010
|
+
{ base: 'lj', letters: '\u01C9' },
|
|
1011
|
+
{ base: 'm', letters: '\u006D\u24DC\uFF4D\u1E3F\u1E41\u1E43\u0271\u026F' },
|
|
1012
|
+
{
|
|
1013
|
+
base: 'n',
|
|
1014
|
+
letters: '\u006E\u24DD\uFF4E\u01F9\u0144\u00F1\u1E45\u0148\u1E47\u0146\u1E4B\u1E49\u019E\u0272\u0149\uA791\uA7A5',
|
|
1015
|
+
},
|
|
1016
|
+
{ base: 'nj', letters: '\u01CC' },
|
|
1017
|
+
{
|
|
1018
|
+
base: 'o',
|
|
1019
|
+
letters: '\u006F\u24DE\uFF4F\u00F2\u00F3\u00F4\u1ED3\u1ED1\u1ED7\u1ED5\u00F5\u1E4D\u022D\u1E4F\u014D\u1E51\u1E53\u014F\u022F\u0231\u00F6\u022B\u1ECF\u0151\u01D2\u020D\u020F\u01A1\u1EDD\u1EDB\u1EE1\u1EDF\u1EE3\u1ECD\u1ED9\u01EB\u01ED\u00F8\u01FF\u0254\uA74B\uA74D\u0275',
|
|
1020
|
+
},
|
|
1021
|
+
{ base: 'oi', letters: '\u01A3' },
|
|
1022
|
+
{ base: 'ou', letters: '\u0223' },
|
|
1023
|
+
{ base: 'oo', letters: '\uA74F' },
|
|
1024
|
+
{
|
|
1025
|
+
base: 'p',
|
|
1026
|
+
letters: '\u0070\u24DF\uFF50\u1E55\u1E57\u01A5\u1D7D\uA751\uA753\uA755',
|
|
1027
|
+
},
|
|
1028
|
+
{ base: 'q', letters: '\u0071\u24E0\uFF51\u024B\uA757\uA759' },
|
|
1029
|
+
{
|
|
1030
|
+
base: 'r',
|
|
1031
|
+
letters: '\u0072\u24E1\uFF52\u0155\u1E59\u0159\u0211\u0213\u1E5B\u1E5D\u0157\u1E5F\u024D\u027D\uA75B\uA7A7\uA783',
|
|
1032
|
+
},
|
|
1033
|
+
{
|
|
1034
|
+
base: 's',
|
|
1035
|
+
letters: '\u0073\u24E2\uFF53\u00DF\u015B\u1E65\u015D\u1E61\u0161\u1E67\u1E63\u1E69\u0219\u015F\u023F\uA7A9\uA785\u1E9B',
|
|
1036
|
+
},
|
|
1037
|
+
{
|
|
1038
|
+
base: 't',
|
|
1039
|
+
letters: '\u0074\u24E3\uFF54\u1E6B\u1E97\u0165\u1E6D\u021B\u0163\u1E71\u1E6F\u0167\u01AD\u0288\u2C66\uA787',
|
|
1040
|
+
},
|
|
1041
|
+
{ base: 'tz', letters: '\uA729' },
|
|
1042
|
+
{
|
|
1043
|
+
base: 'u',
|
|
1044
|
+
letters: '\u0075\u24E4\uFF55\u00F9\u00FA\u00FB\u0169\u1E79\u016B\u1E7B\u016D\u00FC\u01DC\u01D8\u01D6\u01DA\u1EE7\u016F\u0171\u01D4\u0215\u0217\u01B0\u1EEB\u1EE9\u1EEF\u1EED\u1EF1\u1EE5\u1E73\u0173\u1E77\u1E75\u0289',
|
|
1045
|
+
},
|
|
1046
|
+
{ base: 'v', letters: '\u0076\u24E5\uFF56\u1E7D\u1E7F\u028B\uA75F\u028C' },
|
|
1047
|
+
{ base: 'vy', letters: '\uA761' },
|
|
1048
|
+
{
|
|
1049
|
+
base: 'w',
|
|
1050
|
+
letters: '\u0077\u24E6\uFF57\u1E81\u1E83\u0175\u1E87\u1E85\u1E98\u1E89\u2C73',
|
|
1051
|
+
},
|
|
1052
|
+
{ base: 'x', letters: '\u0078\u24E7\uFF58\u1E8B\u1E8D' },
|
|
1053
|
+
{
|
|
1054
|
+
base: 'y',
|
|
1055
|
+
letters: '\u0079\u24E8\uFF59\u1EF3\u00FD\u0177\u1EF9\u0233\u1E8F\u00FF\u1EF7\u1E99\u1EF5\u01B4\u024F\u1EFF',
|
|
1056
|
+
},
|
|
1057
|
+
{
|
|
1058
|
+
base: 'z',
|
|
1059
|
+
letters: '\u007A\u24E9\uFF5A\u017A\u1E91\u017C\u017E\u1E93\u1E95\u01B6\u0225\u0240\u2C6C\uA763',
|
|
1060
|
+
},
|
|
1061
|
+
];
|
|
1062
|
+
/**
|
|
1063
|
+
* Map of letters from diacritic variant to diacritless variant
|
|
1064
|
+
* Contains lowercase and uppercase separatelly
|
|
1065
|
+
*
|
|
1066
|
+
* > "á" => "a"
|
|
1067
|
+
* > "ě" => "e"
|
|
1068
|
+
* > "Ă" => "A"
|
|
1069
|
+
* > ...
|
|
1070
|
+
*
|
|
1071
|
+
* @public exported from `@promptbook/utils`
|
|
1072
|
+
*/
|
|
1073
|
+
const DIACRITIC_VARIANTS_LETTERS = {};
|
|
1074
|
+
// tslint:disable-next-line: prefer-for-of
|
|
1075
|
+
for (let i = 0; i < defaultDiacriticsRemovalMap.length; i++) {
|
|
1076
|
+
const letters = defaultDiacriticsRemovalMap[i].letters;
|
|
1077
|
+
// tslint:disable-next-line: prefer-for-of
|
|
1078
|
+
for (let j = 0; j < letters.length; j++) {
|
|
1079
|
+
DIACRITIC_VARIANTS_LETTERS[letters[j]] = defaultDiacriticsRemovalMap[i].base;
|
|
1080
|
+
}
|
|
1081
|
+
}
|
|
1082
|
+
// <- TODO: [🍓] Put to maker function to save execution time if not needed
|
|
1083
|
+
/*
|
|
1084
|
+
@see https://stackoverflow.com/questions/990904/remove-accents-diacritics-in-a-string-in-javascript
|
|
1085
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
1086
|
+
you may not use this file except in compliance with the License.
|
|
1087
|
+
You may obtain a copy of the License at
|
|
1088
|
+
|
|
1089
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
1090
|
+
|
|
1091
|
+
Unless required by applicable law or agreed to in writing, software
|
|
1092
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
1093
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
1094
|
+
See the License for the specific language governing permissions and
|
|
1095
|
+
limitations under the License.
|
|
1096
|
+
*/
|
|
1097
|
+
|
|
1098
|
+
/**
|
|
1099
|
+
* Removes diacritic marks (accents) from characters in a string.
|
|
1100
|
+
*
|
|
1101
|
+
* @param input The string containing diacritics to be normalized.
|
|
1102
|
+
* @returns The string with diacritics removed or normalized.
|
|
1103
|
+
* @public exported from `@promptbook/utils`
|
|
1104
|
+
*/
|
|
1105
|
+
function removeDiacritics(input) {
|
|
1106
|
+
/*eslint no-control-regex: "off"*/
|
|
1107
|
+
return input.replace(/[^\u0000-\u007E]/g, (a) => {
|
|
1108
|
+
return DIACRITIC_VARIANTS_LETTERS[a] || a;
|
|
1109
|
+
});
|
|
1110
|
+
}
|
|
1111
|
+
/**
|
|
1112
|
+
* TODO: [Ж] Variant for cyrillic (and in general non-latin) letters
|
|
1113
|
+
*/
|
|
1114
|
+
|
|
1115
|
+
/**
|
|
1116
|
+
* Counts number of words in the text
|
|
1117
|
+
*
|
|
1118
|
+
* @public exported from `@promptbook/utils`
|
|
1119
|
+
*/
|
|
1120
|
+
function countWords(text) {
|
|
1121
|
+
text = text.replace(/[\p{Extended_Pictographic}]/gu, 'a');
|
|
1122
|
+
text = removeDiacritics(text);
|
|
1123
|
+
// Add spaces before uppercase letters preceded by lowercase letters (for camelCase)
|
|
1124
|
+
text = text.replace(/([a-z])([A-Z])/g, '$1 $2');
|
|
1125
|
+
return text.split(/[^a-zа-я0-9]+/i).filter((word) => word.length > 0).length;
|
|
1126
|
+
}
|
|
1127
|
+
/**
|
|
1128
|
+
* TODO: [🥴] Implement counting in formats - like JSON, CSV, XML,...
|
|
1129
|
+
*/
|
|
1130
|
+
|
|
1131
|
+
/**
|
|
1132
|
+
* Helper of usage compute
|
|
1133
|
+
*
|
|
1134
|
+
* @param content the content of prompt or response
|
|
1135
|
+
* @returns part of UsageCounts
|
|
1136
|
+
*
|
|
1137
|
+
* @private internal utility of LlmExecutionTools
|
|
1138
|
+
*/
|
|
1139
|
+
function computeUsageCounts(content) {
|
|
1140
|
+
return {
|
|
1141
|
+
charactersCount: { value: countCharacters(content) },
|
|
1142
|
+
wordsCount: { value: countWords(content) },
|
|
1143
|
+
sentencesCount: { value: countSentences(content) },
|
|
1144
|
+
linesCount: { value: countLines(content) },
|
|
1145
|
+
paragraphsCount: { value: countParagraphs(content) },
|
|
1146
|
+
pagesCount: { value: countPages(content) },
|
|
1147
|
+
};
|
|
1148
|
+
}
|
|
1149
|
+
|
|
1150
|
+
/**
|
|
1151
|
+
* Represents the uncertain value
|
|
1152
|
+
*
|
|
1153
|
+
* @public exported from `@promptbook/core`
|
|
1154
|
+
*/
|
|
1155
|
+
const ZERO_VALUE = $deepFreeze({ value: 0 });
|
|
1156
|
+
/**
|
|
1157
|
+
* Represents the uncertain value
|
|
1158
|
+
*
|
|
1159
|
+
* @public exported from `@promptbook/core`
|
|
1160
|
+
*/
|
|
1161
|
+
const UNCERTAIN_ZERO_VALUE = $deepFreeze({ value: 0, isUncertain: true });
|
|
1162
|
+
/**
|
|
1163
|
+
* Represents the usage with no resources consumed
|
|
1164
|
+
*
|
|
1165
|
+
* @public exported from `@promptbook/core`
|
|
1166
|
+
*/
|
|
1167
|
+
$deepFreeze({
|
|
1168
|
+
price: ZERO_VALUE,
|
|
1169
|
+
input: {
|
|
1170
|
+
tokensCount: ZERO_VALUE,
|
|
1171
|
+
charactersCount: ZERO_VALUE,
|
|
1172
|
+
wordsCount: ZERO_VALUE,
|
|
1173
|
+
sentencesCount: ZERO_VALUE,
|
|
1174
|
+
linesCount: ZERO_VALUE,
|
|
1175
|
+
paragraphsCount: ZERO_VALUE,
|
|
1176
|
+
pagesCount: ZERO_VALUE,
|
|
1177
|
+
},
|
|
1178
|
+
output: {
|
|
1179
|
+
tokensCount: ZERO_VALUE,
|
|
1180
|
+
charactersCount: ZERO_VALUE,
|
|
1181
|
+
wordsCount: ZERO_VALUE,
|
|
1182
|
+
sentencesCount: ZERO_VALUE,
|
|
1183
|
+
linesCount: ZERO_VALUE,
|
|
1184
|
+
paragraphsCount: ZERO_VALUE,
|
|
1185
|
+
pagesCount: ZERO_VALUE,
|
|
1186
|
+
},
|
|
1187
|
+
});
|
|
1188
|
+
/**
|
|
1189
|
+
* Represents the usage with unknown resources consumed
|
|
1190
|
+
*
|
|
1191
|
+
* @public exported from `@promptbook/core`
|
|
1192
|
+
*/
|
|
1193
|
+
$deepFreeze({
|
|
1194
|
+
price: UNCERTAIN_ZERO_VALUE,
|
|
1195
|
+
input: {
|
|
1196
|
+
tokensCount: UNCERTAIN_ZERO_VALUE,
|
|
1197
|
+
charactersCount: UNCERTAIN_ZERO_VALUE,
|
|
1198
|
+
wordsCount: UNCERTAIN_ZERO_VALUE,
|
|
1199
|
+
sentencesCount: UNCERTAIN_ZERO_VALUE,
|
|
1200
|
+
linesCount: UNCERTAIN_ZERO_VALUE,
|
|
1201
|
+
paragraphsCount: UNCERTAIN_ZERO_VALUE,
|
|
1202
|
+
pagesCount: UNCERTAIN_ZERO_VALUE,
|
|
1203
|
+
},
|
|
1204
|
+
output: {
|
|
1205
|
+
tokensCount: UNCERTAIN_ZERO_VALUE,
|
|
1206
|
+
charactersCount: UNCERTAIN_ZERO_VALUE,
|
|
1207
|
+
wordsCount: UNCERTAIN_ZERO_VALUE,
|
|
1208
|
+
sentencesCount: UNCERTAIN_ZERO_VALUE,
|
|
1209
|
+
linesCount: UNCERTAIN_ZERO_VALUE,
|
|
1210
|
+
paragraphsCount: UNCERTAIN_ZERO_VALUE,
|
|
1211
|
+
pagesCount: UNCERTAIN_ZERO_VALUE,
|
|
1212
|
+
},
|
|
1213
|
+
});
|
|
1214
|
+
/**
|
|
1215
|
+
* Note: [💞] Ignore a discrepancy between file name and entity name
|
|
1216
|
+
*/
|
|
1217
|
+
|
|
1218
|
+
/**
|
|
1219
|
+
* Make UncertainNumber
|
|
1220
|
+
*
|
|
1221
|
+
* @param value value of the uncertain number, if `NaN` or `undefined`, it will be set to 0 and `isUncertain=true`
|
|
1222
|
+
* @param isUncertain if `true`, the value is uncertain, otherwise depends on the value
|
|
1223
|
+
*
|
|
1224
|
+
* @private utility for initializating UncertainNumber
|
|
1225
|
+
*/
|
|
1226
|
+
function uncertainNumber(value, isUncertain) {
|
|
1227
|
+
if (value === null || value === undefined || Number.isNaN(value)) {
|
|
1228
|
+
return UNCERTAIN_ZERO_VALUE;
|
|
1229
|
+
}
|
|
1230
|
+
if (isUncertain === true) {
|
|
1231
|
+
return { value, isUncertain };
|
|
1232
|
+
}
|
|
1233
|
+
return { value };
|
|
1234
|
+
}
|
|
1235
|
+
|
|
1236
|
+
/**
|
|
1237
|
+
* Function computeUsage will create price per one token based on the string value found on openai page
|
|
1238
|
+
*
|
|
1239
|
+
* @private within the repository, used only as internal helper for `OPENAI_MODELS`
|
|
1240
|
+
*/
|
|
1241
|
+
function computeUsage(value) {
|
|
1242
|
+
const [price, tokens] = value.split(' / ');
|
|
1243
|
+
return parseFloat(price.replace('$', '')) / parseFloat(tokens.replace('M tokens', '')) / 1000000;
|
|
1244
|
+
}
|
|
1245
|
+
|
|
1246
|
+
/**
|
|
1247
|
+
* List of available OpenAI models with pricing
|
|
1248
|
+
*
|
|
1249
|
+
* Note: Done at 2025-05-06
|
|
1250
|
+
*
|
|
1251
|
+
* @see https://platform.openai.com/docs/models/
|
|
1252
|
+
* @see https://openai.com/api/pricing/
|
|
1253
|
+
* @public exported from `@promptbook/openai`
|
|
1254
|
+
*/
|
|
1255
|
+
const OPENAI_MODELS = exportJson({
|
|
1256
|
+
name: 'OPENAI_MODELS',
|
|
1257
|
+
value: [
|
|
1258
|
+
/*/
|
|
1259
|
+
{
|
|
1260
|
+
modelTitle: 'dall-e-3',
|
|
1261
|
+
modelName: 'dall-e-3',
|
|
1262
|
+
},
|
|
1263
|
+
/**/
|
|
1264
|
+
/*/
|
|
1265
|
+
{
|
|
1266
|
+
modelTitle: 'whisper-1',
|
|
1267
|
+
modelName: 'whisper-1',
|
|
1268
|
+
},
|
|
1269
|
+
/**/
|
|
1270
|
+
/**/
|
|
1271
|
+
{
|
|
1272
|
+
modelVariant: 'COMPLETION',
|
|
1273
|
+
modelTitle: 'davinci-002',
|
|
1274
|
+
modelName: 'davinci-002',
|
|
1275
|
+
modelDescription: 'Legacy completion model with strong performance on text generation tasks. Optimized for complex instructions and longer outputs.',
|
|
1276
|
+
pricing: {
|
|
1277
|
+
prompt: computeUsage(`$2.00 / 1M tokens`),
|
|
1278
|
+
output: computeUsage(`$2.00 / 1M tokens`),
|
|
1279
|
+
},
|
|
1280
|
+
},
|
|
1281
|
+
/**/
|
|
1282
|
+
/*/
|
|
1283
|
+
{
|
|
1284
|
+
modelTitle: 'dall-e-2',
|
|
1285
|
+
modelName: 'dall-e-2',
|
|
1286
|
+
},
|
|
1287
|
+
/**/
|
|
1288
|
+
/**/
|
|
1289
|
+
{
|
|
1290
|
+
modelVariant: 'CHAT',
|
|
1291
|
+
modelTitle: 'gpt-3.5-turbo-16k',
|
|
1292
|
+
modelName: 'gpt-3.5-turbo-16k',
|
|
1293
|
+
modelDescription: 'GPT-3.5 Turbo with extended 16k token context length for handling longer conversations and documents.',
|
|
1294
|
+
pricing: {
|
|
1295
|
+
prompt: computeUsage(`$3.00 / 1M tokens`),
|
|
1296
|
+
output: computeUsage(`$4.00 / 1M tokens`),
|
|
1297
|
+
},
|
|
1298
|
+
},
|
|
1299
|
+
/**/
|
|
1300
|
+
/*/
|
|
1301
|
+
{
|
|
1302
|
+
modelTitle: 'tts-1-hd-1106',
|
|
1303
|
+
modelName: 'tts-1-hd-1106',
|
|
1304
|
+
},
|
|
1305
|
+
/**/
|
|
1306
|
+
/*/
|
|
1307
|
+
{
|
|
1308
|
+
modelTitle: 'tts-1-hd',
|
|
1309
|
+
modelName: 'tts-1-hd',
|
|
1310
|
+
},
|
|
1311
|
+
/**/
|
|
1312
|
+
/**/
|
|
1313
|
+
{
|
|
1314
|
+
modelVariant: 'CHAT',
|
|
1315
|
+
modelTitle: 'gpt-4',
|
|
1316
|
+
modelName: 'gpt-4',
|
|
1317
|
+
modelDescription: 'GPT-4 is a powerful language model with enhanced reasoning, instruction-following capabilities, and 8K context window. Optimized for complex tasks requiring deep understanding.',
|
|
1318
|
+
pricing: {
|
|
1319
|
+
prompt: computeUsage(`$30.00 / 1M tokens`),
|
|
1320
|
+
output: computeUsage(`$60.00 / 1M tokens`),
|
|
1321
|
+
},
|
|
1322
|
+
},
|
|
1323
|
+
/**/
|
|
1324
|
+
/**/
|
|
1325
|
+
{
|
|
1326
|
+
modelVariant: 'CHAT',
|
|
1327
|
+
modelTitle: 'gpt-4-32k',
|
|
1328
|
+
modelName: 'gpt-4-32k',
|
|
1329
|
+
modelDescription: 'Extended context version of GPT-4 with a 32K token window for processing very long inputs and generating comprehensive responses for complex tasks.',
|
|
1330
|
+
pricing: {
|
|
1331
|
+
prompt: computeUsage(`$60.00 / 1M tokens`),
|
|
1332
|
+
output: computeUsage(`$120.00 / 1M tokens`),
|
|
1333
|
+
},
|
|
1334
|
+
},
|
|
1335
|
+
/**/
|
|
1336
|
+
/*/
|
|
1337
|
+
{
|
|
1338
|
+
modelVariant: 'CHAT',
|
|
1339
|
+
modelTitle: 'gpt-4-0613',
|
|
1340
|
+
modelName: 'gpt-4-0613',
|
|
1341
|
+
pricing: {
|
|
1342
|
+
prompt: computeUsage(` / 1M tokens`),
|
|
1343
|
+
output: computeUsage(` / 1M tokens`),
|
|
1344
|
+
},
|
|
1345
|
+
},
|
|
1346
|
+
/**/
|
|
1347
|
+
/**/
|
|
1348
|
+
{
|
|
1349
|
+
modelVariant: 'CHAT',
|
|
1350
|
+
modelTitle: 'gpt-4-turbo-2024-04-09',
|
|
1351
|
+
modelName: 'gpt-4-turbo-2024-04-09',
|
|
1352
|
+
modelDescription: 'Latest stable GPT-4 Turbo model from April 2024 with enhanced reasoning and context handling capabilities. Offers 128K context window and improved performance.',
|
|
1353
|
+
pricing: {
|
|
1354
|
+
prompt: computeUsage(`$10.00 / 1M tokens`),
|
|
1355
|
+
output: computeUsage(`$30.00 / 1M tokens`),
|
|
1356
|
+
},
|
|
1357
|
+
},
|
|
1358
|
+
/**/
|
|
1359
|
+
/**/
|
|
1360
|
+
{
|
|
1361
|
+
modelVariant: 'CHAT',
|
|
1362
|
+
modelTitle: 'gpt-3.5-turbo-1106',
|
|
1363
|
+
modelName: 'gpt-3.5-turbo-1106',
|
|
1364
|
+
modelDescription: 'November 2023 version of GPT-3.5 Turbo with improved instruction following and a 16K token context window.',
|
|
1365
|
+
pricing: {
|
|
1366
|
+
prompt: computeUsage(`$1.00 / 1M tokens`),
|
|
1367
|
+
output: computeUsage(`$2.00 / 1M tokens`),
|
|
1368
|
+
},
|
|
1369
|
+
},
|
|
1370
|
+
/**/
|
|
1371
|
+
/**/
|
|
1372
|
+
{
|
|
1373
|
+
modelVariant: 'CHAT',
|
|
1374
|
+
modelTitle: 'gpt-4-turbo',
|
|
1375
|
+
modelName: 'gpt-4-turbo',
|
|
1376
|
+
modelDescription: 'More capable model than GPT-4 with improved instruction following, function calling and a 128K token context window for handling very large documents.',
|
|
1377
|
+
pricing: {
|
|
1378
|
+
prompt: computeUsage(`$10.00 / 1M tokens`),
|
|
1379
|
+
output: computeUsage(`$30.00 / 1M tokens`),
|
|
1380
|
+
},
|
|
1381
|
+
},
|
|
1382
|
+
/**/
|
|
1383
|
+
/**/
|
|
1384
|
+
{
|
|
1385
|
+
modelVariant: 'COMPLETION',
|
|
1386
|
+
modelTitle: 'gpt-3.5-turbo-instruct-0914',
|
|
1387
|
+
modelName: 'gpt-3.5-turbo-instruct-0914',
|
|
1388
|
+
modelDescription: 'September 2023 version of GPT-3.5 Turbo optimized for completion-style instruction following with a 4K context window.',
|
|
1389
|
+
pricing: {
|
|
1390
|
+
prompt: computeUsage(`$1.50 / 1M tokens`),
|
|
1391
|
+
output: computeUsage(`$2.00 / 1M tokens`), // <- For gpt-3.5-turbo-instruct
|
|
1392
|
+
},
|
|
1393
|
+
},
|
|
1394
|
+
/**/
|
|
1395
|
+
/**/
|
|
1396
|
+
{
|
|
1397
|
+
modelVariant: 'COMPLETION',
|
|
1398
|
+
modelTitle: 'gpt-3.5-turbo-instruct',
|
|
1399
|
+
modelName: 'gpt-3.5-turbo-instruct',
|
|
1400
|
+
modelDescription: 'Optimized version of GPT-3.5 for completion-style API with good instruction following and a 4K token context window.',
|
|
1401
|
+
pricing: {
|
|
1402
|
+
prompt: computeUsage(`$1.50 / 1M tokens`),
|
|
1403
|
+
output: computeUsage(`$2.00 / 1M tokens`),
|
|
1404
|
+
},
|
|
1405
|
+
},
|
|
1406
|
+
/**/
|
|
1407
|
+
/*/
|
|
1408
|
+
{
|
|
1409
|
+
modelTitle: 'tts-1',
|
|
1410
|
+
modelName: 'tts-1',
|
|
1411
|
+
},
|
|
1412
|
+
/**/
|
|
1413
|
+
/**/
|
|
1414
|
+
{
|
|
1415
|
+
modelVariant: 'CHAT',
|
|
1416
|
+
modelTitle: 'gpt-3.5-turbo',
|
|
1417
|
+
modelName: 'gpt-3.5-turbo',
|
|
1418
|
+
modelDescription: 'Latest version of GPT-3.5 Turbo with improved performance and instruction following capabilities. Default 4K context window with options for 16K.',
|
|
1419
|
+
pricing: {
|
|
1420
|
+
prompt: computeUsage(`$0.50 / 1M tokens`),
|
|
1421
|
+
output: computeUsage(`$1.50 / 1M tokens`),
|
|
1422
|
+
},
|
|
1423
|
+
},
|
|
1424
|
+
/**/
|
|
1425
|
+
/**/
|
|
1426
|
+
{
|
|
1427
|
+
modelVariant: 'CHAT',
|
|
1428
|
+
modelTitle: 'gpt-3.5-turbo-0301',
|
|
1429
|
+
modelName: 'gpt-3.5-turbo-0301',
|
|
1430
|
+
modelDescription: 'March 2023 version of GPT-3.5 Turbo with a 4K token context window. Legacy model maintained for backward compatibility.',
|
|
1431
|
+
pricing: {
|
|
1432
|
+
prompt: computeUsage(`$1.50 / 1M tokens`),
|
|
1433
|
+
output: computeUsage(`$2.00 / 1M tokens`),
|
|
1434
|
+
},
|
|
1435
|
+
},
|
|
1436
|
+
/**/
|
|
1437
|
+
/**/
|
|
1438
|
+
{
|
|
1439
|
+
modelVariant: 'COMPLETION',
|
|
1440
|
+
modelTitle: 'babbage-002',
|
|
1441
|
+
modelName: 'babbage-002',
|
|
1442
|
+
modelDescription: 'Efficient legacy completion model with a good balance of performance and speed. Suitable for straightforward text generation tasks.',
|
|
1443
|
+
pricing: {
|
|
1444
|
+
prompt: computeUsage(`$0.40 / 1M tokens`),
|
|
1445
|
+
output: computeUsage(`$0.40 / 1M tokens`),
|
|
1446
|
+
},
|
|
1447
|
+
},
|
|
1448
|
+
/**/
|
|
1449
|
+
/**/
|
|
1450
|
+
{
|
|
1451
|
+
modelVariant: 'CHAT',
|
|
1452
|
+
modelTitle: 'gpt-4-1106-preview',
|
|
1453
|
+
modelName: 'gpt-4-1106-preview',
|
|
1454
|
+
modelDescription: 'November 2023 preview version of GPT-4 Turbo with improved instruction following and a 128K token context window.',
|
|
1455
|
+
pricing: {
|
|
1456
|
+
prompt: computeUsage(`$10.00 / 1M tokens`),
|
|
1457
|
+
output: computeUsage(`$30.00 / 1M tokens`),
|
|
1458
|
+
},
|
|
1459
|
+
},
|
|
1460
|
+
/**/
|
|
1461
|
+
/**/
|
|
1462
|
+
{
|
|
1463
|
+
modelVariant: 'CHAT',
|
|
1464
|
+
modelTitle: 'gpt-4-0125-preview',
|
|
1465
|
+
modelName: 'gpt-4-0125-preview',
|
|
1466
|
+
modelDescription: 'January 2024 preview version of GPT-4 Turbo with improved reasoning capabilities and a 128K token context window.',
|
|
1467
|
+
pricing: {
|
|
1468
|
+
prompt: computeUsage(`$10.00 / 1M tokens`),
|
|
1469
|
+
output: computeUsage(`$30.00 / 1M tokens`),
|
|
1470
|
+
},
|
|
1471
|
+
},
|
|
1472
|
+
/**/
|
|
1473
|
+
/*/
|
|
1474
|
+
{
|
|
1475
|
+
modelTitle: 'tts-1-1106',
|
|
1476
|
+
modelName: 'tts-1-1106',
|
|
1477
|
+
},
|
|
1478
|
+
/**/
|
|
1479
|
+
/**/
|
|
1480
|
+
{
|
|
1481
|
+
modelVariant: 'CHAT',
|
|
1482
|
+
modelTitle: 'gpt-3.5-turbo-0125',
|
|
1483
|
+
modelName: 'gpt-3.5-turbo-0125',
|
|
1484
|
+
modelDescription: 'January 2024 version of GPT-3.5 Turbo with improved reasoning capabilities and a 16K token context window.',
|
|
1485
|
+
pricing: {
|
|
1486
|
+
prompt: computeUsage(`$0.50 / 1M tokens`),
|
|
1487
|
+
output: computeUsage(`$1.50 / 1M tokens`),
|
|
1488
|
+
},
|
|
1489
|
+
},
|
|
1490
|
+
/**/
|
|
1491
|
+
/**/
|
|
1492
|
+
{
|
|
1493
|
+
modelVariant: 'CHAT',
|
|
1494
|
+
modelTitle: 'gpt-4-turbo-preview',
|
|
1495
|
+
modelName: 'gpt-4-turbo-preview',
|
|
1496
|
+
modelDescription: 'Preview version of GPT-4 Turbo that points to the latest model version. Features improved instruction following, 128K token context window and lower latency.',
|
|
1497
|
+
pricing: {
|
|
1498
|
+
prompt: computeUsage(`$10.00 / 1M tokens`),
|
|
1499
|
+
output: computeUsage(`$30.00 / 1M tokens`),
|
|
1500
|
+
},
|
|
1501
|
+
},
|
|
1502
|
+
/**/
|
|
1503
|
+
/**/
|
|
1504
|
+
{
|
|
1505
|
+
modelVariant: 'EMBEDDING',
|
|
1506
|
+
modelTitle: 'text-embedding-3-large',
|
|
1507
|
+
modelName: 'text-embedding-3-large',
|
|
1508
|
+
modelDescription: "OpenAI's most capable text embedding model designed for high-quality embeddings for complex similarity tasks and information retrieval.",
|
|
1509
|
+
pricing: {
|
|
1510
|
+
prompt: computeUsage(`$0.13 / 1M tokens`),
|
|
1511
|
+
// TODO: [🏏] Leverage the batch API @see https://platform.openai.com/docs/guides/batch
|
|
1512
|
+
output: 0, // <- Note: [🆖] In Embedding models you dont pay for output
|
|
1513
|
+
},
|
|
1514
|
+
},
|
|
1515
|
+
/**/
|
|
1516
|
+
/**/
|
|
1517
|
+
{
|
|
1518
|
+
modelVariant: 'EMBEDDING',
|
|
1519
|
+
modelTitle: 'text-embedding-3-small',
|
|
1520
|
+
modelName: 'text-embedding-3-small',
|
|
1521
|
+
modelDescription: 'Cost-effective embedding model with good performance for simpler tasks like text similarity and retrieval. Good balance of quality and efficiency.',
|
|
1522
|
+
pricing: {
|
|
1523
|
+
prompt: computeUsage(`$0.02 / 1M tokens`),
|
|
1524
|
+
// TODO: [🏏] Leverage the batch API @see https://platform.openai.com/docs/guides/batch
|
|
1525
|
+
output: 0, // <- Note: [🆖] In Embedding models you dont pay for output
|
|
1526
|
+
},
|
|
1527
|
+
},
|
|
1528
|
+
/**/
|
|
1529
|
+
/**/
|
|
1530
|
+
{
|
|
1531
|
+
modelVariant: 'CHAT',
|
|
1532
|
+
modelTitle: 'gpt-3.5-turbo-0613',
|
|
1533
|
+
modelName: 'gpt-3.5-turbo-0613',
|
|
1534
|
+
modelDescription: 'June 2023 version of GPT-3.5 Turbo with function calling capabilities and a 4K token context window.',
|
|
1535
|
+
pricing: {
|
|
1536
|
+
prompt: computeUsage(`$1.50 / 1M tokens`),
|
|
1537
|
+
output: computeUsage(`$2.00 / 1M tokens`),
|
|
1538
|
+
},
|
|
1539
|
+
},
|
|
1540
|
+
/**/
|
|
1541
|
+
/**/
|
|
1542
|
+
{
|
|
1543
|
+
modelVariant: 'EMBEDDING',
|
|
1544
|
+
modelTitle: 'text-embedding-ada-002',
|
|
1545
|
+
modelName: 'text-embedding-ada-002',
|
|
1546
|
+
modelDescription: 'Legacy text embedding model suitable for text similarity and retrieval augmented generation use cases. Replaced by newer embedding-3 models.',
|
|
1547
|
+
pricing: {
|
|
1548
|
+
prompt: computeUsage(`$0.1 / 1M tokens`),
|
|
1549
|
+
// TODO: [🏏] Leverage the batch API @see https://platform.openai.com/docs/guides/batch
|
|
1550
|
+
output: 0, // <- Note: [🆖] In Embedding models you dont pay for output
|
|
547
1551
|
},
|
|
1552
|
+
},
|
|
1553
|
+
/**/
|
|
1554
|
+
/*/
|
|
1555
|
+
{
|
|
1556
|
+
modelVariant: 'CHAT',
|
|
1557
|
+
modelTitle: 'gpt-4-1106-vision-preview',
|
|
1558
|
+
modelName: 'gpt-4-1106-vision-preview',
|
|
1559
|
+
},
|
|
1560
|
+
/**/
|
|
1561
|
+
/*/
|
|
1562
|
+
{
|
|
1563
|
+
modelVariant: 'CHAT',
|
|
1564
|
+
modelTitle: 'gpt-4-vision-preview',
|
|
1565
|
+
modelName: 'gpt-4-vision-preview',
|
|
1566
|
+
pricing: {
|
|
1567
|
+
prompt: computeUsage(`$10.00 / 1M tokens`),
|
|
1568
|
+
output: computeUsage(`$30.00 / 1M tokens`),
|
|
1569
|
+
},
|
|
1570
|
+
},
|
|
1571
|
+
/**/
|
|
1572
|
+
/**/
|
|
1573
|
+
{
|
|
1574
|
+
modelVariant: 'CHAT',
|
|
1575
|
+
modelTitle: 'gpt-4o-2024-05-13',
|
|
1576
|
+
modelName: 'gpt-4o-2024-05-13',
|
|
1577
|
+
modelDescription: 'May 2024 version of GPT-4o with enhanced multimodal capabilities, improved reasoning, and optimized for vision, audio and chat at lower latencies.',
|
|
1578
|
+
pricing: {
|
|
1579
|
+
prompt: computeUsage(`$5.00 / 1M tokens`),
|
|
1580
|
+
output: computeUsage(`$15.00 / 1M tokens`),
|
|
1581
|
+
},
|
|
1582
|
+
},
|
|
1583
|
+
/**/
|
|
1584
|
+
/**/
|
|
1585
|
+
{
|
|
1586
|
+
modelVariant: 'CHAT',
|
|
1587
|
+
modelTitle: 'gpt-4o',
|
|
1588
|
+
modelName: 'gpt-4o',
|
|
1589
|
+
modelDescription: "OpenAI's most advanced multimodal model optimized for performance, speed, and cost. Capable of vision, reasoning, and high quality text generation.",
|
|
1590
|
+
pricing: {
|
|
1591
|
+
prompt: computeUsage(`$5.00 / 1M tokens`),
|
|
1592
|
+
output: computeUsage(`$15.00 / 1M tokens`),
|
|
1593
|
+
},
|
|
1594
|
+
},
|
|
1595
|
+
/**/
|
|
1596
|
+
/**/
|
|
1597
|
+
{
|
|
1598
|
+
modelVariant: 'CHAT',
|
|
1599
|
+
modelTitle: 'gpt-4o-mini',
|
|
1600
|
+
modelName: 'gpt-4o-mini',
|
|
1601
|
+
modelDescription: 'Smaller, more cost-effective version of GPT-4o with good performance across text, vision, and audio tasks at reduced complexity.',
|
|
1602
|
+
pricing: {
|
|
1603
|
+
prompt: computeUsage(`$0.15 / 1M tokens`),
|
|
1604
|
+
output: computeUsage(`$0.60 / 1M tokens`),
|
|
1605
|
+
},
|
|
1606
|
+
},
|
|
1607
|
+
/**/
|
|
1608
|
+
/**/
|
|
1609
|
+
{
|
|
1610
|
+
modelVariant: 'CHAT',
|
|
1611
|
+
modelTitle: 'o1-preview',
|
|
1612
|
+
modelName: 'o1-preview',
|
|
1613
|
+
modelDescription: 'Advanced reasoning model with exceptional performance on complex logical, mathematical, and analytical tasks. Built for deep reasoning and specialized professional tasks.',
|
|
1614
|
+
pricing: {
|
|
1615
|
+
prompt: computeUsage(`$15.00 / 1M tokens`),
|
|
1616
|
+
output: computeUsage(`$60.00 / 1M tokens`),
|
|
1617
|
+
},
|
|
1618
|
+
},
|
|
1619
|
+
/**/
|
|
1620
|
+
/**/
|
|
1621
|
+
{
|
|
1622
|
+
modelVariant: 'CHAT',
|
|
1623
|
+
modelTitle: 'o1-preview-2024-09-12',
|
|
1624
|
+
modelName: 'o1-preview-2024-09-12',
|
|
1625
|
+
modelDescription: 'September 2024 version of O1 preview with specialized reasoning capabilities for complex tasks requiring precise analytical thinking.',
|
|
1626
|
+
// <- TODO: [💩] Some better system to organize these date suffixes and versions
|
|
1627
|
+
pricing: {
|
|
1628
|
+
prompt: computeUsage(`$15.00 / 1M tokens`),
|
|
1629
|
+
output: computeUsage(`$60.00 / 1M tokens`),
|
|
1630
|
+
},
|
|
1631
|
+
},
|
|
1632
|
+
/**/
|
|
1633
|
+
/**/
|
|
1634
|
+
{
|
|
1635
|
+
modelVariant: 'CHAT',
|
|
1636
|
+
modelTitle: 'o1-mini',
|
|
1637
|
+
modelName: 'o1-mini',
|
|
1638
|
+
modelDescription: 'Smaller, cost-effective version of the O1 model with good performance on reasoning tasks while maintaining efficiency for everyday analytical use.',
|
|
1639
|
+
pricing: {
|
|
1640
|
+
prompt: computeUsage(`$3.00 / 1M tokens`),
|
|
1641
|
+
output: computeUsage(`$12.00 / 1M tokens`),
|
|
1642
|
+
},
|
|
1643
|
+
},
|
|
1644
|
+
/**/
|
|
1645
|
+
/**/
|
|
1646
|
+
{
|
|
1647
|
+
modelVariant: 'CHAT',
|
|
1648
|
+
modelTitle: 'o1',
|
|
1649
|
+
modelName: 'o1',
|
|
1650
|
+
modelDescription: "OpenAI's advanced reasoning model focused on logic and problem-solving. Designed for complex analytical tasks with rigorous step-by-step reasoning. 128K context window.",
|
|
1651
|
+
pricing: {
|
|
1652
|
+
prompt: computeUsage(`$15.00 / 1M tokens`),
|
|
1653
|
+
output: computeUsage(`$60.00 / 1M tokens`),
|
|
1654
|
+
},
|
|
1655
|
+
},
|
|
1656
|
+
/**/
|
|
1657
|
+
/**/
|
|
1658
|
+
{
|
|
1659
|
+
modelVariant: 'CHAT',
|
|
1660
|
+
modelTitle: 'o3-mini',
|
|
1661
|
+
modelName: 'o3-mini',
|
|
1662
|
+
modelDescription: 'Cost-effective reasoning model optimized for academic and scientific problem-solving. Efficient performance on STEM tasks with deep mathematical and scientific knowledge. 128K context window.',
|
|
1663
|
+
pricing: {
|
|
1664
|
+
prompt: computeUsage(`$3.00 / 1M tokens`),
|
|
1665
|
+
output: computeUsage(`$12.00 / 1M tokens`),
|
|
1666
|
+
// <- TODO: !! Unsure, check the pricing
|
|
1667
|
+
},
|
|
1668
|
+
},
|
|
1669
|
+
/**/
|
|
1670
|
+
/**/
|
|
1671
|
+
{
|
|
1672
|
+
modelVariant: 'CHAT',
|
|
1673
|
+
modelTitle: 'o1-mini-2024-09-12',
|
|
1674
|
+
modelName: 'o1-mini-2024-09-12',
|
|
1675
|
+
modelDescription: "September 2024 version of O1-mini with balanced reasoning capabilities and cost-efficiency. Good for analytical tasks that don't require the full O1 model.",
|
|
1676
|
+
pricing: {
|
|
1677
|
+
prompt: computeUsage(`$3.00 / 1M tokens`),
|
|
1678
|
+
output: computeUsage(`$12.00 / 1M tokens`),
|
|
1679
|
+
},
|
|
1680
|
+
},
|
|
1681
|
+
/**/
|
|
1682
|
+
/**/
|
|
1683
|
+
{
|
|
1684
|
+
modelVariant: 'CHAT',
|
|
1685
|
+
modelTitle: 'gpt-3.5-turbo-16k-0613',
|
|
1686
|
+
modelName: 'gpt-3.5-turbo-16k-0613',
|
|
1687
|
+
modelDescription: 'June 2023 version of GPT-3.5 Turbo with extended 16k token context window for processing longer conversations and documents.',
|
|
1688
|
+
pricing: {
|
|
1689
|
+
prompt: computeUsage(`$3.00 / 1M tokens`),
|
|
1690
|
+
output: computeUsage(`$4.00 / 1M tokens`),
|
|
1691
|
+
},
|
|
1692
|
+
},
|
|
1693
|
+
/**/
|
|
1694
|
+
// <- [🕕]
|
|
1695
|
+
],
|
|
1696
|
+
});
|
|
1697
|
+
/**
|
|
1698
|
+
* Note: [🤖] Add models of new variant
|
|
1699
|
+
* TODO: [🧠] Some mechanism to propagate unsureness
|
|
1700
|
+
* TODO: [🎰] Some mechanism to auto-update available models
|
|
1701
|
+
* TODO: [🎰][👮♀️] Make this list dynamic - dynamically can be listed modelNames but not modelVariant, legacy status, context length and pricing
|
|
1702
|
+
* TODO: [🧠][👮♀️] Put here more info like description, isVision, trainingDateCutoff, languages, strengths ( Top-level performance, intelligence, fluency, and understanding), contextWindow,...
|
|
1703
|
+
* @see https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4
|
|
1704
|
+
* @see https://openai.com/api/pricing/
|
|
1705
|
+
* @see /other/playground/playground.ts
|
|
1706
|
+
* TODO: [🍓][💩] Make better
|
|
1707
|
+
* TODO: Change model titles to human eg: "gpt-4-turbo-2024-04-09" -> "GPT-4 Turbo (2024-04-09)"
|
|
1708
|
+
* TODO: [🚸] Not all models are compatible with JSON mode, add this information here and use it
|
|
1709
|
+
* Note: [💞] Ignore a discrepancy between file name and entity name
|
|
1710
|
+
*/
|
|
1711
|
+
|
|
1712
|
+
/**
|
|
1713
|
+
* Computes the usage of the OpenAI API based on the response from OpenAI
|
|
1714
|
+
*
|
|
1715
|
+
* @param promptContent The content of the prompt
|
|
1716
|
+
* @param resultContent The content of the result (for embedding prompts or failed prompts pass empty string)
|
|
1717
|
+
* @param rawResponse The raw response from OpenAI API
|
|
1718
|
+
* @throws {PipelineExecutionError} If the usage is not defined in the response from OpenAI
|
|
1719
|
+
* @private internal utility of `OpenAiExecutionTools`
|
|
1720
|
+
*/
|
|
1721
|
+
function computeOpenAiUsage(promptContent, // <- Note: Intentionally using [] to access type properties to bring jsdoc from Prompt/PromptResult to consumer
|
|
1722
|
+
resultContent, rawResponse) {
|
|
1723
|
+
var _a, _b;
|
|
1724
|
+
if (rawResponse.usage === undefined) {
|
|
1725
|
+
throw new PipelineExecutionError('The usage is not defined in the response from OpenAI');
|
|
1726
|
+
}
|
|
1727
|
+
if (((_a = rawResponse.usage) === null || _a === void 0 ? void 0 : _a.prompt_tokens) === undefined) {
|
|
1728
|
+
throw new PipelineExecutionError('In OpenAI response `usage.prompt_tokens` not defined');
|
|
1729
|
+
}
|
|
1730
|
+
const inputTokens = rawResponse.usage.prompt_tokens;
|
|
1731
|
+
const outputTokens = ((_b = rawResponse.usage) === null || _b === void 0 ? void 0 : _b.completion_tokens) || 0;
|
|
1732
|
+
let isUncertain = false;
|
|
1733
|
+
let modelInfo = OPENAI_MODELS.find((model) => model.modelName === rawResponse.model);
|
|
1734
|
+
if (modelInfo === undefined) {
|
|
1735
|
+
// Note: Model is not in the list of known models, fallback to the family of the models and mark price as uncertain
|
|
1736
|
+
modelInfo = OPENAI_MODELS.find((model) => (rawResponse.model || SALT_NONCE).startsWith(model.modelName));
|
|
1737
|
+
if (modelInfo !== undefined) {
|
|
1738
|
+
isUncertain = true;
|
|
1739
|
+
}
|
|
1740
|
+
}
|
|
1741
|
+
let price;
|
|
1742
|
+
if (modelInfo === undefined || modelInfo.pricing === undefined) {
|
|
1743
|
+
price = uncertainNumber();
|
|
1744
|
+
}
|
|
1745
|
+
else {
|
|
1746
|
+
price = uncertainNumber(inputTokens * modelInfo.pricing.prompt + outputTokens * modelInfo.pricing.output, isUncertain);
|
|
1747
|
+
}
|
|
1748
|
+
return {
|
|
1749
|
+
price,
|
|
1750
|
+
input: {
|
|
1751
|
+
tokensCount: uncertainNumber(rawResponse.usage.prompt_tokens),
|
|
1752
|
+
...computeUsageCounts(promptContent),
|
|
1753
|
+
},
|
|
1754
|
+
output: {
|
|
1755
|
+
tokensCount: uncertainNumber(outputTokens),
|
|
1756
|
+
...computeUsageCounts(resultContent),
|
|
1757
|
+
},
|
|
1758
|
+
};
|
|
1759
|
+
}
|
|
1760
|
+
/**
|
|
1761
|
+
* TODO: [🤝] DRY Maybe some common abstraction between `computeOpenAiUsage` and `computeAnthropicClaudeUsage`
|
|
1762
|
+
*/
|
|
1763
|
+
|
|
1764
|
+
/**
|
|
1765
|
+
* Execution Tools for calling OpenAI API
|
|
1766
|
+
*
|
|
1767
|
+
* @public exported from `@promptbook/openai`
|
|
1768
|
+
*/
|
|
1769
|
+
class OpenAiExecutionTools {
|
|
1770
|
+
/**
|
|
1771
|
+
* Creates OpenAI Execution Tools.
|
|
1772
|
+
*
|
|
1773
|
+
* @param options which are relevant are directly passed to the OpenAI client
|
|
1774
|
+
*/
|
|
1775
|
+
constructor(options) {
|
|
1776
|
+
this.options = options;
|
|
1777
|
+
/**
|
|
1778
|
+
* OpenAI API client.
|
|
1779
|
+
*/
|
|
1780
|
+
this.client = null;
|
|
1781
|
+
// TODO: Allow configuring rate limits via options
|
|
1782
|
+
this.limiter = new Bottleneck({
|
|
1783
|
+
minTime: 60000 / (this.options.maxRequestsPerMinute || DEFAULT_MAX_REQUESTS_PER_MINUTE),
|
|
548
1784
|
});
|
|
549
1785
|
}
|
|
1786
|
+
get title() {
|
|
1787
|
+
return 'OpenAI';
|
|
1788
|
+
}
|
|
1789
|
+
get description() {
|
|
1790
|
+
return 'Use all models provided by OpenAI';
|
|
1791
|
+
}
|
|
1792
|
+
async getClient() {
|
|
1793
|
+
if (this.client === null) {
|
|
1794
|
+
// Note: Passing only OpenAI relevant options to OpenAI constructor
|
|
1795
|
+
const openAiOptions = { ...this.options };
|
|
1796
|
+
delete openAiOptions.isVerbose;
|
|
1797
|
+
delete openAiOptions.userId;
|
|
1798
|
+
this.client = new OpenAI(openAiOptions);
|
|
1799
|
+
}
|
|
1800
|
+
return this.client;
|
|
1801
|
+
}
|
|
1802
|
+
/*
|
|
1803
|
+
Note: Commenting this out to avoid circular dependency
|
|
1804
|
+
/**
|
|
1805
|
+
* Create (sub)tools for calling OpenAI API Assistants
|
|
1806
|
+
*
|
|
1807
|
+
* @param assistantId Which assistant to use
|
|
1808
|
+
* @returns Tools for calling OpenAI API Assistants with same token
|
|
1809
|
+
* /
|
|
1810
|
+
public createAssistantSubtools(assistantId: string_token): OpenAiAssistantExecutionTools {
|
|
1811
|
+
return new OpenAiAssistantExecutionTools({ ...this.options, assistantId });
|
|
1812
|
+
}
|
|
1813
|
+
*/
|
|
1814
|
+
/**
|
|
1815
|
+
* Check the `options` passed to `constructor`
|
|
1816
|
+
*/
|
|
1817
|
+
async checkConfiguration() {
|
|
1818
|
+
await this.getClient();
|
|
1819
|
+
// TODO: [🎍] Do here a real check that API is online, working and API key is correct
|
|
1820
|
+
}
|
|
1821
|
+
/**
|
|
1822
|
+
* List all available OpenAI models that can be used
|
|
1823
|
+
*/
|
|
1824
|
+
async listModels() {
|
|
1825
|
+
/*
|
|
1826
|
+
Note: Dynamic lising of the models
|
|
1827
|
+
const models = await this.openai.models.list({});
|
|
1828
|
+
|
|
1829
|
+
console.log({ models });
|
|
1830
|
+
console.log(models.data);
|
|
1831
|
+
*/
|
|
1832
|
+
const client = await this.getClient();
|
|
1833
|
+
const rawModelsList = await client.models.list();
|
|
1834
|
+
const availableModels = rawModelsList.data
|
|
1835
|
+
.sort((a, b) => (a.created > b.created ? 1 : -1))
|
|
1836
|
+
.map((modelFromApi) => {
|
|
1837
|
+
// TODO: !!!! What about other model compatibilities?
|
|
1838
|
+
const modelFromList = OPENAI_MODELS.find(({ modelName }) => modelName === modelFromApi.id ||
|
|
1839
|
+
modelName.startsWith(modelFromApi.id) ||
|
|
1840
|
+
modelFromApi.id.startsWith(modelName));
|
|
1841
|
+
if (modelFromList !== undefined) {
|
|
1842
|
+
return modelFromList;
|
|
1843
|
+
}
|
|
1844
|
+
return {
|
|
1845
|
+
modelVariant: 'CHAT',
|
|
1846
|
+
modelTitle: modelFromApi.id,
|
|
1847
|
+
modelName: modelFromApi.id,
|
|
1848
|
+
modelDescription: '',
|
|
1849
|
+
};
|
|
1850
|
+
});
|
|
1851
|
+
return availableModels;
|
|
1852
|
+
}
|
|
1853
|
+
/**
|
|
1854
|
+
* Calls OpenAI API to use a chat model.
|
|
1855
|
+
*/
|
|
1856
|
+
async callChatModel(prompt) {
|
|
1857
|
+
var _a;
|
|
1858
|
+
if (this.options.isVerbose) {
|
|
1859
|
+
console.info('💬 OpenAI callChatModel call', { prompt });
|
|
1860
|
+
}
|
|
1861
|
+
const { content, parameters, modelRequirements, format } = prompt;
|
|
1862
|
+
const client = await this.getClient();
|
|
1863
|
+
// TODO: [☂] Use here more modelRequirements
|
|
1864
|
+
if (modelRequirements.modelVariant !== 'CHAT') {
|
|
1865
|
+
throw new PipelineExecutionError('Use callChatModel only for CHAT variant');
|
|
1866
|
+
}
|
|
1867
|
+
const modelName = modelRequirements.modelName || this.getDefaultChatModel().modelName;
|
|
1868
|
+
const modelSettings = {
|
|
1869
|
+
model: modelName,
|
|
1870
|
+
max_tokens: modelRequirements.maxTokens,
|
|
1871
|
+
// <- TODO: [🌾] Make some global max cap for maxTokens
|
|
1872
|
+
temperature: modelRequirements.temperature,
|
|
1873
|
+
// <- TODO: [🈁] Use `seed` here AND/OR use is `isDeterministic` for entire execution tools
|
|
1874
|
+
// <- Note: [🧆]
|
|
1875
|
+
}; // <- TODO: [💩] Guard here types better
|
|
1876
|
+
if (format === 'JSON') {
|
|
1877
|
+
modelSettings.response_format = {
|
|
1878
|
+
type: 'json_object',
|
|
1879
|
+
};
|
|
1880
|
+
}
|
|
1881
|
+
// <- TODO: [🚸] Not all models are compatible with JSON mode
|
|
1882
|
+
// > 'response_format' of type 'json_object' is not supported with this model.
|
|
1883
|
+
const rawPromptContent = templateParameters(content, { ...parameters, modelName });
|
|
1884
|
+
const rawRequest = {
|
|
1885
|
+
...modelSettings,
|
|
1886
|
+
messages: [
|
|
1887
|
+
...(modelRequirements.systemMessage === undefined
|
|
1888
|
+
? []
|
|
1889
|
+
: [
|
|
1890
|
+
{
|
|
1891
|
+
role: 'system',
|
|
1892
|
+
content: modelRequirements.systemMessage,
|
|
1893
|
+
},
|
|
1894
|
+
]),
|
|
1895
|
+
{
|
|
1896
|
+
role: 'user',
|
|
1897
|
+
content: rawPromptContent,
|
|
1898
|
+
},
|
|
1899
|
+
],
|
|
1900
|
+
user: (_a = this.options.userId) === null || _a === void 0 ? void 0 : _a.toString(),
|
|
1901
|
+
};
|
|
1902
|
+
const start = $getCurrentDate();
|
|
1903
|
+
if (this.options.isVerbose) {
|
|
1904
|
+
console.info(colors.bgWhite('rawRequest'), JSON.stringify(rawRequest, null, 4));
|
|
1905
|
+
}
|
|
1906
|
+
const rawResponse = await this.limiter
|
|
1907
|
+
.schedule(() => client.chat.completions.create(rawRequest))
|
|
1908
|
+
.catch((error) => {
|
|
1909
|
+
assertsError(error);
|
|
1910
|
+
if (this.options.isVerbose) {
|
|
1911
|
+
console.info(colors.bgRed('error'), error);
|
|
1912
|
+
}
|
|
1913
|
+
throw error;
|
|
1914
|
+
});
|
|
1915
|
+
if (this.options.isVerbose) {
|
|
1916
|
+
console.info(colors.bgWhite('rawResponse'), JSON.stringify(rawResponse, null, 4));
|
|
1917
|
+
}
|
|
1918
|
+
const complete = $getCurrentDate();
|
|
1919
|
+
if (!rawResponse.choices[0]) {
|
|
1920
|
+
throw new PipelineExecutionError('No choises from OpenAI');
|
|
1921
|
+
}
|
|
1922
|
+
if (rawResponse.choices.length > 1) {
|
|
1923
|
+
// TODO: This should be maybe only warning
|
|
1924
|
+
throw new PipelineExecutionError('More than one choise from OpenAI');
|
|
1925
|
+
}
|
|
1926
|
+
const resultContent = rawResponse.choices[0].message.content;
|
|
1927
|
+
const usage = computeOpenAiUsage(content || '', resultContent || '', rawResponse);
|
|
1928
|
+
if (resultContent === null) {
|
|
1929
|
+
throw new PipelineExecutionError('No response message from OpenAI');
|
|
1930
|
+
}
|
|
1931
|
+
return exportJson({
|
|
1932
|
+
name: 'promptResult',
|
|
1933
|
+
message: `Result of \`OpenAiExecutionTools.callChatModel\``,
|
|
1934
|
+
order: [],
|
|
1935
|
+
value: {
|
|
1936
|
+
content: resultContent,
|
|
1937
|
+
modelName: rawResponse.model || modelName,
|
|
1938
|
+
timing: {
|
|
1939
|
+
start,
|
|
1940
|
+
complete,
|
|
1941
|
+
},
|
|
1942
|
+
usage,
|
|
1943
|
+
rawPromptContent,
|
|
1944
|
+
rawRequest,
|
|
1945
|
+
rawResponse,
|
|
1946
|
+
// <- [🗯]
|
|
1947
|
+
},
|
|
1948
|
+
});
|
|
1949
|
+
}
|
|
1950
|
+
/**
|
|
1951
|
+
* Calls OpenAI API to use a complete model.
|
|
1952
|
+
*/
|
|
1953
|
+
async callCompletionModel(prompt) {
|
|
1954
|
+
var _a;
|
|
1955
|
+
if (this.options.isVerbose) {
|
|
1956
|
+
console.info('🖋 OpenAI callCompletionModel call', { prompt });
|
|
1957
|
+
}
|
|
1958
|
+
const { content, parameters, modelRequirements } = prompt;
|
|
1959
|
+
const client = await this.getClient();
|
|
1960
|
+
// TODO: [☂] Use here more modelRequirements
|
|
1961
|
+
if (modelRequirements.modelVariant !== 'COMPLETION') {
|
|
1962
|
+
throw new PipelineExecutionError('Use callCompletionModel only for COMPLETION variant');
|
|
1963
|
+
}
|
|
1964
|
+
const modelName = modelRequirements.modelName || this.getDefaultCompletionModel().modelName;
|
|
1965
|
+
const modelSettings = {
|
|
1966
|
+
model: modelName,
|
|
1967
|
+
max_tokens: modelRequirements.maxTokens || 2000,
|
|
1968
|
+
// <- TODO: [🌾] Make some global max cap for maxTokens
|
|
1969
|
+
temperature: modelRequirements.temperature,
|
|
1970
|
+
// <- TODO: [🈁] Use `seed` here AND/OR use is `isDeterministic` for entire execution tools
|
|
1971
|
+
// <- Note: [🧆]
|
|
1972
|
+
};
|
|
1973
|
+
const rawPromptContent = templateParameters(content, { ...parameters, modelName });
|
|
1974
|
+
const rawRequest = {
|
|
1975
|
+
...modelSettings,
|
|
1976
|
+
prompt: rawPromptContent,
|
|
1977
|
+
user: (_a = this.options.userId) === null || _a === void 0 ? void 0 : _a.toString(),
|
|
1978
|
+
};
|
|
1979
|
+
const start = $getCurrentDate();
|
|
1980
|
+
if (this.options.isVerbose) {
|
|
1981
|
+
console.info(colors.bgWhite('rawRequest'), JSON.stringify(rawRequest, null, 4));
|
|
1982
|
+
}
|
|
1983
|
+
const rawResponse = await this.limiter
|
|
1984
|
+
.schedule(() => client.completions.create(rawRequest))
|
|
1985
|
+
.catch((error) => {
|
|
1986
|
+
assertsError(error);
|
|
1987
|
+
if (this.options.isVerbose) {
|
|
1988
|
+
console.info(colors.bgRed('error'), error);
|
|
1989
|
+
}
|
|
1990
|
+
throw error;
|
|
1991
|
+
});
|
|
1992
|
+
if (this.options.isVerbose) {
|
|
1993
|
+
console.info(colors.bgWhite('rawResponse'), JSON.stringify(rawResponse, null, 4));
|
|
1994
|
+
}
|
|
1995
|
+
const complete = $getCurrentDate();
|
|
1996
|
+
if (!rawResponse.choices[0]) {
|
|
1997
|
+
throw new PipelineExecutionError('No choises from OpenAI');
|
|
1998
|
+
}
|
|
1999
|
+
if (rawResponse.choices.length > 1) {
|
|
2000
|
+
// TODO: This should be maybe only warning
|
|
2001
|
+
throw new PipelineExecutionError('More than one choise from OpenAI');
|
|
2002
|
+
}
|
|
2003
|
+
const resultContent = rawResponse.choices[0].text;
|
|
2004
|
+
const usage = computeOpenAiUsage(content || '', resultContent || '', rawResponse);
|
|
2005
|
+
return exportJson({
|
|
2006
|
+
name: 'promptResult',
|
|
2007
|
+
message: `Result of \`OpenAiExecutionTools.callCompletionModel\``,
|
|
2008
|
+
order: [],
|
|
2009
|
+
value: {
|
|
2010
|
+
content: resultContent,
|
|
2011
|
+
modelName: rawResponse.model || modelName,
|
|
2012
|
+
timing: {
|
|
2013
|
+
start,
|
|
2014
|
+
complete,
|
|
2015
|
+
},
|
|
2016
|
+
usage,
|
|
2017
|
+
rawPromptContent,
|
|
2018
|
+
rawRequest,
|
|
2019
|
+
rawResponse,
|
|
2020
|
+
// <- [🗯]
|
|
2021
|
+
},
|
|
2022
|
+
});
|
|
2023
|
+
}
|
|
2024
|
+
/**
|
|
2025
|
+
* Calls OpenAI API to use a embedding model
|
|
2026
|
+
*/
|
|
2027
|
+
async callEmbeddingModel(prompt) {
|
|
2028
|
+
if (this.options.isVerbose) {
|
|
2029
|
+
console.info('🖋 OpenAI embedding call', { prompt });
|
|
2030
|
+
}
|
|
2031
|
+
const { content, parameters, modelRequirements } = prompt;
|
|
2032
|
+
const client = await this.getClient();
|
|
2033
|
+
// TODO: [☂] Use here more modelRequirements
|
|
2034
|
+
if (modelRequirements.modelVariant !== 'EMBEDDING') {
|
|
2035
|
+
throw new PipelineExecutionError('Use embed only for EMBEDDING variant');
|
|
2036
|
+
}
|
|
2037
|
+
const modelName = modelRequirements.modelName || this.getDefaultEmbeddingModel().modelName;
|
|
2038
|
+
const rawPromptContent = templateParameters(content, { ...parameters, modelName });
|
|
2039
|
+
const rawRequest = {
|
|
2040
|
+
input: rawPromptContent,
|
|
2041
|
+
model: modelName,
|
|
2042
|
+
};
|
|
2043
|
+
const start = $getCurrentDate();
|
|
2044
|
+
if (this.options.isVerbose) {
|
|
2045
|
+
console.info(colors.bgWhite('rawRequest'), JSON.stringify(rawRequest, null, 4));
|
|
2046
|
+
}
|
|
2047
|
+
const rawResponse = await this.limiter
|
|
2048
|
+
.schedule(() => client.embeddings.create(rawRequest))
|
|
2049
|
+
.catch((error) => {
|
|
2050
|
+
assertsError(error);
|
|
2051
|
+
if (this.options.isVerbose) {
|
|
2052
|
+
console.info(colors.bgRed('error'), error);
|
|
2053
|
+
}
|
|
2054
|
+
throw error;
|
|
2055
|
+
});
|
|
2056
|
+
if (this.options.isVerbose) {
|
|
2057
|
+
console.info(colors.bgWhite('rawResponse'), JSON.stringify(rawResponse, null, 4));
|
|
2058
|
+
}
|
|
2059
|
+
const complete = $getCurrentDate();
|
|
2060
|
+
if (rawResponse.data.length !== 1) {
|
|
2061
|
+
throw new PipelineExecutionError(`Expected exactly 1 data item in response, got ${rawResponse.data.length}`);
|
|
2062
|
+
}
|
|
2063
|
+
const resultContent = rawResponse.data[0].embedding;
|
|
2064
|
+
const usage = computeOpenAiUsage(content || '', '',
|
|
2065
|
+
// <- Note: Embedding does not have result content
|
|
2066
|
+
rawResponse);
|
|
2067
|
+
return exportJson({
|
|
2068
|
+
name: 'promptResult',
|
|
2069
|
+
message: `Result of \`OpenAiExecutionTools.callEmbeddingModel\``,
|
|
2070
|
+
order: [],
|
|
2071
|
+
value: {
|
|
2072
|
+
content: resultContent,
|
|
2073
|
+
modelName: rawResponse.model || modelName,
|
|
2074
|
+
timing: {
|
|
2075
|
+
start,
|
|
2076
|
+
complete,
|
|
2077
|
+
},
|
|
2078
|
+
usage,
|
|
2079
|
+
rawPromptContent,
|
|
2080
|
+
rawRequest,
|
|
2081
|
+
rawResponse,
|
|
2082
|
+
// <- [🗯]
|
|
2083
|
+
},
|
|
2084
|
+
});
|
|
2085
|
+
}
|
|
2086
|
+
// <- Note: [🤖] callXxxModel
|
|
2087
|
+
/**
|
|
2088
|
+
* Get the model that should be used as default
|
|
2089
|
+
*/
|
|
2090
|
+
getDefaultModel(defaultModelName) {
|
|
2091
|
+
// Note: Match exact or prefix for model families
|
|
2092
|
+
const model = OPENAI_MODELS.find(({ modelName }) => modelName === defaultModelName || modelName.startsWith(defaultModelName));
|
|
2093
|
+
if (model === undefined) {
|
|
2094
|
+
throw new UnexpectedError(spaceTrim((block) => `
|
|
2095
|
+
Cannot find model in OpenAI models with name "${defaultModelName}" which should be used as default.
|
|
2096
|
+
|
|
2097
|
+
Available models:
|
|
2098
|
+
${block(OPENAI_MODELS.map(({ modelName }) => `- "${modelName}"`).join('\n'))}
|
|
2099
|
+
|
|
2100
|
+
`));
|
|
2101
|
+
}
|
|
2102
|
+
return model;
|
|
2103
|
+
}
|
|
2104
|
+
/**
|
|
2105
|
+
* Default model for chat variant.
|
|
2106
|
+
*/
|
|
2107
|
+
getDefaultChatModel() {
|
|
2108
|
+
return this.getDefaultModel('gpt-4o');
|
|
2109
|
+
}
|
|
2110
|
+
/**
|
|
2111
|
+
* Default model for completion variant.
|
|
2112
|
+
*/
|
|
2113
|
+
getDefaultCompletionModel() {
|
|
2114
|
+
return this.getDefaultModel('gpt-3.5-turbo-instruct');
|
|
2115
|
+
}
|
|
2116
|
+
/**
|
|
2117
|
+
* Default model for completion variant.
|
|
2118
|
+
*/
|
|
2119
|
+
getDefaultEmbeddingModel() {
|
|
2120
|
+
return this.getDefaultModel('text-embedding-3-large');
|
|
2121
|
+
}
|
|
550
2122
|
}
|
|
2123
|
+
/**
|
|
2124
|
+
* TODO: [🧠][🧙♂️] Maybe there can be some wizzard for thoose who want to use just OpenAI
|
|
2125
|
+
* TODO: Maybe Create some common util for callChatModel and callCompletionModel
|
|
2126
|
+
* TODO: Maybe make custom OpenAiError
|
|
2127
|
+
* TODO: [🧠][🈁] Maybe use `isDeterministic` from options
|
|
2128
|
+
* TODO: [🧠][🌰] Allow to pass `title` for tracking purposes
|
|
2129
|
+
*/
|
|
2130
|
+
|
|
2131
|
+
/**
|
|
2132
|
+
* Execution Tools for calling OpenAI API
|
|
2133
|
+
*
|
|
2134
|
+
* Note: This can be also used for other OpenAI compatible APIs, like Ollama
|
|
2135
|
+
*
|
|
2136
|
+
* @public exported from `@promptbook/openai`
|
|
2137
|
+
*/
|
|
2138
|
+
const createOpenAiExecutionTools = Object.assign((options) => {
|
|
2139
|
+
// TODO: [🧠][main] !!4 If browser, auto add `dangerouslyAllowBrowser`
|
|
2140
|
+
if (($isRunningInBrowser() || $isRunningInWebWorker()) && !options.dangerouslyAllowBrowser) {
|
|
2141
|
+
options = { ...options, dangerouslyAllowBrowser: true };
|
|
2142
|
+
}
|
|
2143
|
+
return new OpenAiExecutionTools(options);
|
|
2144
|
+
}, {
|
|
2145
|
+
packageName: '@promptbook/openai',
|
|
2146
|
+
className: 'OpenAiExecutionTools',
|
|
2147
|
+
});
|
|
2148
|
+
/**
|
|
2149
|
+
* TODO: [🦺] Is there some way how to put `packageName` and `className` on top and function definition on bottom?
|
|
2150
|
+
* TODO: [🎶] Naming "constructor" vs "creator" vs "factory"
|
|
2151
|
+
*/
|
|
2152
|
+
|
|
2153
|
+
/**
|
|
2154
|
+
* Default base URL for Ollama API
|
|
2155
|
+
*
|
|
2156
|
+
* @public exported from `@promptbook/ollama`
|
|
2157
|
+
*/
|
|
2158
|
+
const DEFAULT_OLLAMA_BASE_URL = 'http://localhost:11434'; // <- TODO: !!!! What is the correct base URL? /v1?
|
|
551
2159
|
|
|
552
2160
|
/**
|
|
553
2161
|
* Execution Tools for calling Ollama API
|
|
554
2162
|
*
|
|
555
2163
|
* @public exported from `@promptbook/ollama`
|
|
556
2164
|
*/
|
|
557
|
-
const createOllamaExecutionTools = Object.assign((
|
|
2165
|
+
const createOllamaExecutionTools = Object.assign((ollamaOptions) => {
|
|
2166
|
+
const openAiCompatibleOptions = {
|
|
2167
|
+
baseURL: DEFAULT_OLLAMA_BASE_URL,
|
|
2168
|
+
...ollamaOptions,
|
|
2169
|
+
userId: 'ollama',
|
|
2170
|
+
};
|
|
2171
|
+
// TODO: !!!! Listing the models - do it dynamically in OpenAiExecutionTools
|
|
2172
|
+
// TODO: !!!! Do not allow to create Assistant from OpenAi compatible tools
|
|
2173
|
+
return createOpenAiExecutionTools(openAiCompatibleOptions);
|
|
2174
|
+
}, {
|
|
558
2175
|
packageName: '@promptbook/ollama',
|
|
559
2176
|
className: 'OllamaExecutionTools',
|
|
560
2177
|
});
|
|
@@ -737,5 +2354,5 @@ const _OllamaRegistration = $llmToolsRegister.register(createOllamaExecutionTool
|
|
|
737
2354
|
* Note: [💞] Ignore a discrepancy between file name and entity name
|
|
738
2355
|
*/
|
|
739
2356
|
|
|
740
|
-
export { BOOK_LANGUAGE_VERSION,
|
|
2357
|
+
export { BOOK_LANGUAGE_VERSION, DEFAULT_OLLAMA_BASE_URL, PROMPTBOOK_ENGINE_VERSION, _OllamaRegistration, createOllamaExecutionTools };
|
|
741
2358
|
//# sourceMappingURL=index.es.js.map
|