@promptbook/ollama 0.103.0-67 → 0.103.0-68

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.
@@ -8,7 +8,7 @@ import type { Usage } from './Usage';
8
8
  *
9
9
  * @see https://github.com/webgptorg/promptbook#prompt-result
10
10
  */
11
- export type PromptResult = CompletionPromptResult | ChatPromptResult | EmbeddingPromptResult;
11
+ export type PromptResult = CompletionPromptResult | ChatPromptResult | ImagePromptResult | EmbeddingPromptResult;
12
12
  /**
13
13
  * Completion prompt result
14
14
  *
@@ -22,6 +22,12 @@ export type CompletionPromptResult = CommonPromptResult;
22
22
  * Note: [🚉] This is fully serializable as JSON
23
23
  */
24
24
  export type ChatPromptResult = CommonPromptResult & {};
25
+ /**
26
+ * Image prompt result
27
+ *
28
+ * Note: [🚉] This is fully serializable as JSON
29
+ */
30
+ export type ImagePromptResult = CommonPromptResult;
25
31
  /**
26
32
  * Embedding prompt result
27
33
  *
@@ -38,6 +38,10 @@ export declare class OllamaExecutionTools extends OpenAiCompatibleExecutionTools
38
38
  * Default model for completion variant.
39
39
  */
40
40
  protected getDefaultEmbeddingModel(): AvailableModel;
41
+ /**
42
+ * Default model for image generation variant.
43
+ */
44
+ protected getDefaultImageGenerationModel(): AvailableModel;
41
45
  }
42
46
  /**
43
47
  * TODO: [🛄] Some way how to re-wrap the errors from `OpenAiCompatibleExecutionTools`
@@ -1,7 +1,7 @@
1
1
  import OpenAI from 'openai';
2
2
  import type { AvailableModel } from '../../execution/AvailableModel';
3
3
  import type { LlmExecutionTools } from '../../execution/LlmExecutionTools';
4
- import type { ChatPromptResult, CompletionPromptResult, EmbeddingPromptResult } from '../../execution/PromptResult';
4
+ import type { ChatPromptResult, CompletionPromptResult, EmbeddingPromptResult, ImagePromptResult } from '../../execution/PromptResult';
5
5
  import type { Usage } from '../../execution/Usage';
6
6
  import type { Prompt } from '../../types/Prompt';
7
7
  import type { string_markdown, string_markdown_text, string_model_name, string_title } from '../../types/typeAliases';
@@ -63,6 +63,14 @@ export declare abstract class OpenAiCompatibleExecutionTools implements LlmExecu
63
63
  * Internal method that handles parameter retry for embedding model calls
64
64
  */
65
65
  private callEmbeddingModelWithRetry;
66
+ /**
67
+ * Calls OpenAI compatible API to use a image generation model
68
+ */
69
+ callImageGenerationModel(prompt: Pick<Prompt, 'content' | 'parameters' | 'modelRequirements'>): Promise<ImagePromptResult>;
70
+ /**
71
+ * Internal method that handles parameter retry for image generation model calls
72
+ */
73
+ private callImageGenerationModelWithRetry;
66
74
  /**
67
75
  * Get the model that should be used as default
68
76
  */
@@ -89,6 +97,10 @@ export declare abstract class OpenAiCompatibleExecutionTools implements LlmExecu
89
97
  * Default model for completion variant.
90
98
  */
91
99
  protected abstract getDefaultEmbeddingModel(): AvailableModel;
100
+ /**
101
+ * Default model for image generation variant.
102
+ */
103
+ protected abstract getDefaultImageGenerationModel(): AvailableModel;
92
104
  /**
93
105
  * Makes a request with retry logic for network errors like ECONNRESET
94
106
  */
@@ -35,4 +35,8 @@ export declare class OpenAiExecutionTools extends OpenAiCompatibleExecutionTools
35
35
  * Default model for completion variant.
36
36
  */
37
37
  protected getDefaultEmbeddingModel(): AvailableModel;
38
+ /**
39
+ * Default model for image generation variant.
40
+ */
41
+ protected getDefaultImageGenerationModel(): AvailableModel;
38
42
  }
@@ -1,15 +1,11 @@
1
1
  import type { AvailableModel } from '../../execution/AvailableModel';
2
2
  import type { LlmExecutionTools } from '../../execution/LlmExecutionTools';
3
3
  import type { Usage } from '../../execution/Usage';
4
- import type { string_markdown } from '../../types/typeAliases';
5
- import type { string_markdown_text } from '../../types/typeAliases';
6
- import type { string_model_name } from '../../types/typeAliases';
7
- import type { string_title } from '../../types/typeAliases';
4
+ import type { string_markdown, string_markdown_text, string_model_name, string_title } from '../../types/typeAliases';
8
5
  import { RemoteLlmExecutionTools } from '../remote/RemoteLlmExecutionTools';
9
6
  import { computeOpenAiUsage } from './computeOpenAiUsage';
10
7
  import { OpenAiCompatibleExecutionTools } from './OpenAiCompatibleExecutionTools';
11
- import type { OpenAiCompatibleExecutionToolsNonProxiedOptions } from './OpenAiCompatibleExecutionToolsOptions';
12
- import type { OpenAiCompatibleExecutionToolsOptions } from './OpenAiCompatibleExecutionToolsOptions';
8
+ import type { OpenAiCompatibleExecutionToolsNonProxiedOptions, OpenAiCompatibleExecutionToolsOptions } from './OpenAiCompatibleExecutionToolsOptions';
13
9
  /**
14
10
  * Execution Tools for calling OpenAI compatible API
15
11
  *
@@ -67,6 +63,10 @@ export declare class HardcodedOpenAiCompatibleExecutionTools extends OpenAiCompa
67
63
  * Default model for completion variant.
68
64
  */
69
65
  protected getDefaultEmbeddingModel(): AvailableModel;
66
+ /**
67
+ * Default model for image generation variant.
68
+ */
69
+ protected getDefaultImageGenerationModel(): AvailableModel;
70
70
  }
71
71
  /**
72
72
  * TODO: [🦺] Is there some way how to put `packageName` and `className` on top and function definition on bottom?
@@ -7,7 +7,7 @@ import type { number_model_temperature, number_seed, string_model_name, string_s
7
7
  * Note: [🚉] This is fully serializable as JSON
8
8
  * @see https://github.com/webgptorg/promptbook#model-requirements
9
9
  */
10
- export type ModelRequirements = CompletionModelRequirements | ChatModelRequirements | EmbeddingModelRequirements;
10
+ export type ModelRequirements = CompletionModelRequirements | ChatModelRequirements | ImageGenerationModelRequirements | EmbeddingModelRequirements;
11
11
  /**
12
12
  * Model requirements for the completion variant
13
13
  *
@@ -34,6 +34,17 @@ export type ChatModelRequirements = CommonModelRequirements & {
34
34
  */
35
35
  readonly systemMessage?: string_system_message;
36
36
  };
37
+ /**
38
+ * Model requirements for the image generation variant
39
+ *
40
+ * Note: [🚉] This is fully serializable as JSON
41
+ */
42
+ export type ImageGenerationModelRequirements = CommonModelRequirements & {
43
+ /**
44
+ * Image generation model variant
45
+ */
46
+ modelVariant: 'IMAGE_GENERATION';
47
+ };
37
48
  /**
38
49
  * Model requirements for the embedding variant
39
50
  *
@@ -59,6 +70,7 @@ export type CommonModelRequirements = {
59
70
  * There are 3 variants:
60
71
  * - **COMPLETION** - model that takes prompt and writes the rest of the text
61
72
  * - **CHAT** - model that takes prompt and previous messages and returns response
73
+ * - **IMAGE_GENERATION** - model that takes prompt and returns image
62
74
  * - **EMBEDDING** - model that takes prompt and returns embedding
63
75
  * <- [🤖]
64
76
  */
@@ -12,4 +12,4 @@ export type ModelVariant = TupleToUnion<typeof MODEL_VARIANTS>;
12
12
  * @see {@link ModelVariant}
13
13
  * @public exported from `@promptbook/core`
14
14
  */
15
- export declare const MODEL_VARIANTS: readonly ["COMPLETION", "CHAT", "EMBEDDING"];
15
+ export declare const MODEL_VARIANTS: readonly ["COMPLETION", "CHAT", "IMAGE_GENERATION", "EMBEDDING"];
@@ -4,6 +4,7 @@ import type { Expectations } from '../pipeline/PipelineJson/Expectations';
4
4
  import type { ChatModelRequirements } from './ModelRequirements';
5
5
  import type { CompletionModelRequirements } from './ModelRequirements';
6
6
  import type { EmbeddingModelRequirements } from './ModelRequirements';
7
+ import type { ImageGenerationModelRequirements } from './ModelRequirements';
7
8
  import type { ModelRequirements } from './ModelRequirements';
8
9
  import type { Parameters } from './typeAliases';
9
10
  import type { string_pipeline_url_with_task_hash } from './typeAliases';
@@ -17,7 +18,7 @@ import type { string_title } from './typeAliases';
17
18
  * Note: [🚉] This is fully serializable as JSON
18
19
  * @see https://github.com/webgptorg/promptbook#prompt
19
20
  */
20
- export type Prompt = CompletionPrompt | ChatPrompt | EmbeddingPrompt;
21
+ export type Prompt = CompletionPrompt | ChatPrompt | ImagePrompt | EmbeddingPrompt;
21
22
  /**
22
23
  * Completion prompt
23
24
  *
@@ -44,6 +45,17 @@ export type ChatPrompt = CommonPrompt & {
44
45
  */
45
46
  thread?: ChatMessage[];
46
47
  };
48
+ /**
49
+ * Image prompt
50
+ *
51
+ * Note: [🚉] This is fully serializable as JSON
52
+ */
53
+ export type ImagePrompt = CommonPrompt & {
54
+ /**
55
+ * Requirements for image generation model
56
+ */
57
+ modelRequirements: ImageGenerationModelRequirements;
58
+ };
47
59
  /**
48
60
  * Embedding prompt
49
61
  *
@@ -15,7 +15,7 @@ export declare const BOOK_LANGUAGE_VERSION: string_semantic_version;
15
15
  export declare const PROMPTBOOK_ENGINE_VERSION: string_promptbook_version;
16
16
  /**
17
17
  * Represents the version string of the Promptbook engine.
18
- * It follows semantic versioning (e.g., `0.103.0-66`).
18
+ * It follows semantic versioning (e.g., `0.103.0-67`).
19
19
  *
20
20
  * @generated
21
21
  */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@promptbook/ollama",
3
- "version": "0.103.0-67",
3
+ "version": "0.103.0-68",
4
4
  "description": "Promptbook: Turn your company's scattered knowledge into AI ready books",
5
5
  "private": false,
6
6
  "sideEffects": false,
@@ -94,7 +94,7 @@
94
94
  "module": "./esm/index.es.js",
95
95
  "typings": "./esm/typings/src/_packages/ollama.index.d.ts",
96
96
  "peerDependencies": {
97
- "@promptbook/core": "0.103.0-67"
97
+ "@promptbook/core": "0.103.0-68"
98
98
  },
99
99
  "dependencies": {
100
100
  "bottleneck": "2.19.5",
package/umd/index.umd.js CHANGED
@@ -25,7 +25,7 @@
25
25
  * @generated
26
26
  * @see https://github.com/webgptorg/promptbook
27
27
  */
28
- const PROMPTBOOK_ENGINE_VERSION = '0.103.0-67';
28
+ const PROMPTBOOK_ENGINE_VERSION = '0.103.0-68';
29
29
  /**
30
30
  * TODO: string_promptbook_version should be constrained to the all versions of Promptbook engine
31
31
  * Note: [💞] Ignore a discrepancy between file name and entity name
@@ -2174,12 +2174,18 @@
2174
2174
  },
2175
2175
  },
2176
2176
  /**/
2177
- /*/
2178
- {
2179
- modelTitle: 'dall-e-3',
2180
- modelName: 'dall-e-3',
2181
- },
2182
- /**/
2177
+ /**/
2178
+ {
2179
+ modelVariant: 'IMAGE_GENERATION',
2180
+ modelTitle: 'dall-e-3',
2181
+ modelName: 'dall-e-3',
2182
+ modelDescription: 'DALL·E 3 is the latest version of the DALL·E art generation model. It understands significantly more nuance and detail than our previous systems, allowing you to easily translate your ideas into exceptionally accurate images.',
2183
+ pricing: {
2184
+ prompt: 0,
2185
+ output: 0.04,
2186
+ },
2187
+ },
2188
+ /**/
2183
2189
  /*/
2184
2190
  {
2185
2191
  modelTitle: 'whisper-1',
@@ -2198,12 +2204,18 @@
2198
2204
  },
2199
2205
  },
2200
2206
  /**/
2201
- /*/
2202
- {
2203
- modelTitle: 'dall-e-2',
2204
- modelName: 'dall-e-2',
2205
- },
2206
- /**/
2207
+ /**/
2208
+ {
2209
+ modelVariant: 'IMAGE_GENERATION',
2210
+ modelTitle: 'dall-e-2',
2211
+ modelName: 'dall-e-2',
2212
+ modelDescription: 'DALL·E 2 is an AI system that can create realistic images and art from a description in natural language.',
2213
+ pricing: {
2214
+ prompt: 0,
2215
+ output: 0.02,
2216
+ },
2217
+ },
2218
+ /**/
2207
2219
  /**/
2208
2220
  {
2209
2221
  modelVariant: 'CHAT',
@@ -3414,6 +3426,151 @@
3414
3426
  return this.callEmbeddingModelWithRetry(prompt, modifiedModelRequirements, attemptStack, retriedUnsupportedParameters);
3415
3427
  }
3416
3428
  }
3429
+ /**
3430
+ * Calls OpenAI compatible API to use a image generation model
3431
+ */
3432
+ async callImageGenerationModel(prompt) {
3433
+ // Deep clone prompt and modelRequirements to avoid mutation across calls
3434
+ const clonedPrompt = JSON.parse(JSON.stringify(prompt));
3435
+ const retriedUnsupportedParameters = new Set();
3436
+ return this.callImageGenerationModelWithRetry(clonedPrompt, clonedPrompt.modelRequirements, [], retriedUnsupportedParameters);
3437
+ }
3438
+ /**
3439
+ * Internal method that handles parameter retry for image generation model calls
3440
+ */
3441
+ async callImageGenerationModelWithRetry(prompt, currentModelRequirements, attemptStack = [], retriedUnsupportedParameters = new Set()) {
3442
+ var _a, _b;
3443
+ if (this.options.isVerbose) {
3444
+ console.info(`🎨 ${this.title} callImageGenerationModel call`, { prompt, currentModelRequirements });
3445
+ }
3446
+ const { content, parameters } = prompt;
3447
+ const client = await this.getClient();
3448
+ // TODO: [☂] Use here more modelRequirements
3449
+ if (currentModelRequirements.modelVariant !== 'IMAGE_GENERATION') {
3450
+ throw new PipelineExecutionError('Use callImageGenerationModel only for IMAGE_GENERATION variant');
3451
+ }
3452
+ const modelName = currentModelRequirements.modelName || this.getDefaultImageGenerationModel().modelName;
3453
+ const modelSettings = {
3454
+ model: modelName,
3455
+ // size: currentModelRequirements.size,
3456
+ // quality: currentModelRequirements.quality,
3457
+ // style: currentModelRequirements.style,
3458
+ };
3459
+ const rawPromptContent = templateParameters(content, { ...parameters, modelName });
3460
+ const rawRequest = {
3461
+ ...modelSettings,
3462
+ prompt: rawPromptContent,
3463
+ user: (_a = this.options.userId) === null || _a === void 0 ? void 0 : _a.toString(),
3464
+ response_format: 'url', // TODO: [🧠] Maybe allow b64_json
3465
+ };
3466
+ const start = $getCurrentDate();
3467
+ if (this.options.isVerbose) {
3468
+ console.info(colors__default["default"].bgWhite('rawRequest'), JSON.stringify(rawRequest, null, 4));
3469
+ }
3470
+ try {
3471
+ const rawResponse = await this.limiter
3472
+ .schedule(() => this.makeRequestWithNetworkRetry(() => client.images.generate(rawRequest)))
3473
+ .catch((error) => {
3474
+ assertsError(error);
3475
+ if (this.options.isVerbose) {
3476
+ console.info(colors__default["default"].bgRed('error'), error);
3477
+ }
3478
+ throw error;
3479
+ });
3480
+ if (this.options.isVerbose) {
3481
+ console.info(colors__default["default"].bgWhite('rawResponse'), JSON.stringify(rawResponse, null, 4));
3482
+ }
3483
+ const complete = $getCurrentDate();
3484
+ if (!rawResponse.data[0]) {
3485
+ throw new PipelineExecutionError(`No choises from ${this.title}`);
3486
+ }
3487
+ if (rawResponse.data.length > 1) {
3488
+ throw new PipelineExecutionError(`More than one choise from ${this.title}`);
3489
+ }
3490
+ const resultContent = rawResponse.data[0].url;
3491
+ const modelInfo = this.HARDCODED_MODELS.find((model) => model.modelName === modelName);
3492
+ const price = ((_b = modelInfo === null || modelInfo === void 0 ? void 0 : modelInfo.pricing) === null || _b === void 0 ? void 0 : _b.output) ? uncertainNumber(modelInfo.pricing.output) : uncertainNumber();
3493
+ return exportJson({
3494
+ name: 'promptResult',
3495
+ message: `Result of \`OpenAiCompatibleExecutionTools.callImageGenerationModel\``,
3496
+ order: [],
3497
+ value: {
3498
+ content: resultContent,
3499
+ modelName: modelName,
3500
+ timing: {
3501
+ start,
3502
+ complete,
3503
+ },
3504
+ usage: {
3505
+ price,
3506
+ input: {
3507
+ tokensCount: uncertainNumber(0),
3508
+ ...computeUsageCounts(rawPromptContent),
3509
+ },
3510
+ output: {
3511
+ tokensCount: uncertainNumber(0),
3512
+ ...computeUsageCounts(''),
3513
+ },
3514
+ },
3515
+ rawPromptContent,
3516
+ rawRequest,
3517
+ rawResponse,
3518
+ },
3519
+ });
3520
+ }
3521
+ catch (error) {
3522
+ assertsError(error);
3523
+ if (!isUnsupportedParameterError(error)) {
3524
+ if (attemptStack.length > 0) {
3525
+ throw new PipelineExecutionError(`All attempts failed. Attempt history:\n` +
3526
+ attemptStack
3527
+ .map((a, i) => ` ${i + 1}. Model: ${a.modelName}` +
3528
+ (a.unsupportedParameter ? `, Stripped: ${a.unsupportedParameter}` : '') +
3529
+ `, Error: ${a.errorMessage}` +
3530
+ (a.stripped ? ' (stripped and retried)' : ''))
3531
+ .join('\n') +
3532
+ `\nFinal error: ${error.message}`);
3533
+ }
3534
+ throw error;
3535
+ }
3536
+ const unsupportedParameter = parseUnsupportedParameterError(error.message);
3537
+ if (!unsupportedParameter) {
3538
+ if (this.options.isVerbose) {
3539
+ console.warn(colors__default["default"].bgYellow('Warning'), 'Could not parse unsupported parameter from error:', error.message);
3540
+ }
3541
+ throw error;
3542
+ }
3543
+ const retryKey = `${modelName}-${unsupportedParameter}`;
3544
+ if (retriedUnsupportedParameters.has(retryKey)) {
3545
+ attemptStack.push({
3546
+ modelName,
3547
+ unsupportedParameter,
3548
+ errorMessage: error.message,
3549
+ stripped: true,
3550
+ });
3551
+ throw new PipelineExecutionError(`All attempts failed. Attempt history:\n` +
3552
+ attemptStack
3553
+ .map((a, i) => ` ${i + 1}. Model: ${a.modelName}` +
3554
+ (a.unsupportedParameter ? `, Stripped: ${a.unsupportedParameter}` : '') +
3555
+ `, Error: ${a.errorMessage}` +
3556
+ (a.stripped ? ' (stripped and retried)' : ''))
3557
+ .join('\n') +
3558
+ `\nFinal error: ${error.message}`);
3559
+ }
3560
+ retriedUnsupportedParameters.add(retryKey);
3561
+ if (this.options.isVerbose) {
3562
+ console.warn(colors__default["default"].bgYellow('Warning'), `Removing unsupported parameter '${unsupportedParameter}' for model '${modelName}' and retrying request`);
3563
+ }
3564
+ attemptStack.push({
3565
+ modelName,
3566
+ unsupportedParameter,
3567
+ errorMessage: error.message,
3568
+ stripped: true,
3569
+ });
3570
+ const modifiedModelRequirements = removeUnsupportedModelRequirement(currentModelRequirements, unsupportedParameter);
3571
+ return this.callImageGenerationModelWithRetry(prompt, modifiedModelRequirements, attemptStack, retriedUnsupportedParameters);
3572
+ }
3573
+ }
3417
3574
  // <- Note: [🤖] callXxxModel
3418
3575
  /**
3419
3576
  * Get the model that should be used as default
@@ -3844,6 +4001,13 @@
3844
4001
  return this.getDefaultModel('text-embedding-3-large'); // <- TODO: [🧠] Pick the best default model
3845
4002
  // <- TODO: [🛄]
3846
4003
  }
4004
+ /**
4005
+ * Default model for image generation variant.
4006
+ */
4007
+ getDefaultImageGenerationModel() {
4008
+ return this.getDefaultModel('!!!'); // <- TODO: [🧠] Pick the best default model
4009
+ // <- TODO: [🛄]
4010
+ }
3847
4011
  }
3848
4012
  /**
3849
4013
  * TODO: [🛄] Some way how to re-wrap the errors from `OpenAiCompatibleExecutionTools`