@promptbook/openai 0.103.0-47 → 0.103.0-49

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/esm/index.es.js +165 -34
  2. package/esm/index.es.js.map +1 -1
  3. package/esm/typings/servers.d.ts +1 -0
  4. package/esm/typings/src/_packages/core.index.d.ts +6 -0
  5. package/esm/typings/src/_packages/types.index.d.ts +4 -0
  6. package/esm/typings/src/_packages/utils.index.d.ts +2 -0
  7. package/esm/typings/src/book-2.0/agent-source/AgentBasicInformation.d.ts +17 -3
  8. package/esm/typings/src/book-2.0/agent-source/AgentSourceParseResult.d.ts +2 -1
  9. package/esm/typings/src/book-2.0/agent-source/computeAgentHash.d.ts +8 -0
  10. package/esm/typings/src/book-2.0/agent-source/computeAgentHash.test.d.ts +1 -0
  11. package/esm/typings/src/book-2.0/agent-source/createDefaultAgentName.d.ts +8 -0
  12. package/esm/typings/src/book-2.0/agent-source/normalizeAgentName.d.ts +9 -0
  13. package/esm/typings/src/book-2.0/agent-source/normalizeAgentName.test.d.ts +1 -0
  14. package/esm/typings/src/book-2.0/agent-source/parseAgentSourceWithCommitments.d.ts +1 -1
  15. package/esm/typings/src/collection/agent-collection/constructors/agent-collection-in-supabase/AgentCollectionInSupabase.d.ts +14 -8
  16. package/esm/typings/src/collection/agent-collection/constructors/agent-collection-in-supabase/AgentCollectionInSupabaseOptions.d.ts +10 -0
  17. package/esm/typings/src/collection/agent-collection/constructors/agent-collection-in-supabase/AgentsDatabaseSchema.d.ts +57 -32
  18. package/esm/typings/src/commitments/MESSAGE/InitialMessageCommitmentDefinition.d.ts +28 -0
  19. package/esm/typings/src/commitments/index.d.ts +2 -1
  20. package/esm/typings/src/config.d.ts +1 -0
  21. package/esm/typings/src/errors/DatabaseError.d.ts +2 -2
  22. package/esm/typings/src/errors/WrappedError.d.ts +2 -2
  23. package/esm/typings/src/execution/ExecutionTask.d.ts +2 -2
  24. package/esm/typings/src/execution/LlmExecutionTools.d.ts +6 -1
  25. package/esm/typings/src/llm-providers/_common/register/$provideLlmToolsForWizardOrCli.d.ts +2 -2
  26. package/esm/typings/src/llm-providers/_common/utils/assertUniqueModels.d.ts +12 -0
  27. package/esm/typings/src/llm-providers/agent/Agent.d.ts +17 -4
  28. package/esm/typings/src/llm-providers/agent/AgentLlmExecutionTools.d.ts +10 -1
  29. package/esm/typings/src/llm-providers/agent/RemoteAgent.d.ts +6 -2
  30. package/esm/typings/src/llm-providers/openai/OpenAiAssistantExecutionTools.d.ts +30 -4
  31. package/esm/typings/src/llm-providers/openai/openai-models.test.d.ts +4 -0
  32. package/esm/typings/src/remote-server/startAgentServer.d.ts +2 -2
  33. package/esm/typings/src/remote-server/startRemoteServer.d.ts +1 -2
  34. package/esm/typings/src/transpilers/openai-sdk/register.d.ts +1 -1
  35. package/esm/typings/src/types/typeAliases.d.ts +6 -0
  36. package/esm/typings/src/utils/color/Color.d.ts +7 -0
  37. package/esm/typings/src/utils/color/Color.test.d.ts +1 -0
  38. package/esm/typings/src/utils/environment/$getGlobalScope.d.ts +2 -2
  39. package/esm/typings/src/utils/misc/computeHash.d.ts +11 -0
  40. package/esm/typings/src/utils/misc/computeHash.test.d.ts +1 -0
  41. package/esm/typings/src/utils/normalization/normalize-to-kebab-case.d.ts +2 -0
  42. package/esm/typings/src/utils/normalization/normalizeTo_PascalCase.d.ts +3 -0
  43. package/esm/typings/src/utils/normalization/normalizeTo_camelCase.d.ts +2 -0
  44. package/esm/typings/src/utils/normalization/titleToName.d.ts +2 -0
  45. package/esm/typings/src/utils/organization/$sideEffect.d.ts +2 -2
  46. package/esm/typings/src/utils/organization/$side_effect.d.ts +2 -2
  47. package/esm/typings/src/utils/organization/TODO_USE.d.ts +2 -2
  48. package/esm/typings/src/utils/organization/keepUnused.d.ts +2 -2
  49. package/esm/typings/src/utils/organization/preserve.d.ts +3 -3
  50. package/esm/typings/src/utils/organization/really_any.d.ts +7 -0
  51. package/esm/typings/src/utils/serialization/asSerializable.d.ts +2 -2
  52. package/esm/typings/src/version.d.ts +1 -1
  53. package/package.json +3 -4
  54. package/umd/index.umd.js +170 -38
  55. package/umd/index.umd.js.map +1 -1
@@ -0,0 +1,4 @@
1
+ export {};
2
+ /**
3
+ * TODO: [🧠] Maybe do this test for all model providers + boilerplate
4
+ */
@@ -9,7 +9,7 @@ type AgentsServerOptions = {
9
9
  port: number_port;
10
10
  };
11
11
  /**
12
- * !!!!!
12
+ * [🐱‍🚀]
13
13
  * Remote server is a proxy server that uses its execution tools internally and exposes the executor interface externally.
14
14
  *
15
15
  * You can simply use `RemoteExecutionTools` on client-side javascript and connect to your remote server.
@@ -17,7 +17,7 @@ type AgentsServerOptions = {
17
17
  *
18
18
  * @see https://github.com/webgptorg/promptbook#remote-server
19
19
  * @public exported from `@promptbook/remote-server`
20
- * <- TODO: !!!! Maybe change to `@promptbook/agent-server`
20
+ * <- TODO: [🐱‍🚀] Change to `@promptbook/agent-server`
21
21
  */
22
22
  export declare function startAgentServer(options: AgentsServerOptions): Promise<TODO_any>;
23
23
  export {};
@@ -11,8 +11,7 @@ import type { RemoteServerOptions } from './types/RemoteServerOptions';
11
11
  */
12
12
  export declare function startRemoteServer<TCustomOptions = undefined>(options: RemoteServerOptions<TCustomOptions>): RemoteServer;
13
13
  /**
14
- * TODO !!!! Add agent
15
- * TODO: !!!! Allow to chat with agents directly via remote server
14
+
16
15
  * TODO: [🕋] Use here `aboutPromptbookInformation`
17
16
  * TODO: [🌡] Add CORS and security - probably via `helmet`
18
17
  * TODO: Split this file into multiple functions - handler for each request
@@ -7,7 +7,7 @@ import type { Registration } from '../../utils/misc/$Register';
7
7
  * @public exported from `@promptbook/wizard`
8
8
  * @public exported from `@promptbook/cli`
9
9
  *
10
- * TODO: !!!! Which package should export this?
10
+ * TODO: [🧠] Which package should export this?
11
11
  */
12
12
  export declare const _OpenAiSdkTranspilerRegistration: Registration;
13
13
  /**
@@ -148,6 +148,12 @@ export type string_agent_name = string;
148
148
  * For example `"My AI Assistant"`
149
149
  */
150
150
  export type string_agent_name_in_book = string;
151
+ /**
152
+ * Semantic helper
153
+ *
154
+ * For example `"b126926439c5fcb83609888a11283723c1ef137c0ad599a77a1be81812bd221d"`
155
+ */
156
+ export type string_agent_hash = string_sha256;
151
157
  /**
152
158
  * Unstructured description of the persona
153
159
  *
@@ -59,6 +59,13 @@ export declare class Color {
59
59
  * @returns Color object
60
60
  */
61
61
  private static fromHex3;
62
+ /**
63
+ * Creates a new Color instance from color in hex format with 4 digits (with alpha channel)
64
+ *
65
+ * @param color in hex for example `09df`
66
+ * @returns Color object
67
+ */
68
+ private static fromHex4;
62
69
  /**
63
70
  * Creates a new Color instance from color in hex format with 6 color digits (without alpha channel)
64
71
  *
@@ -0,0 +1 @@
1
+ export {};
@@ -1,4 +1,4 @@
1
- import type { really_any } from '../organization/really_any';
1
+ import type { chococake } from '../organization/really_any';
2
2
  /**
3
3
  * Safely retrieves the global scope object (window in browser, global in Node.js)
4
4
  * regardless of the JavaScript environment in which the code is running
@@ -7,4 +7,4 @@ import type { really_any } from '../organization/really_any';
7
7
  *
8
8
  * @private internal function of `$Register`
9
9
  */
10
- export declare function $getGlobalScope(): really_any;
10
+ export declare function $getGlobalScope(): chococake;
@@ -0,0 +1,11 @@
1
+ import { string_sha256 } from '../../types/typeAliases';
2
+ import { really_unknown } from '../organization/really_unknown';
3
+ /**
4
+ * Computes SHA-256 hash of the given object
5
+ *
6
+ * @public exported from `@promptbook/utils`
7
+ */
8
+ export declare function computeHash(value: really_unknown): string_sha256;
9
+ /**
10
+ * TODO: [🥬][🥬] Use this ACRY
11
+ */
@@ -0,0 +1 @@
1
+ export {};
@@ -9,6 +9,8 @@ export type string_kebab_case = string;
9
9
  /**
10
10
  * Converts a given text to kebab-case format.
11
11
  *
12
+ * Note: [🔂] This function is idempotent.
13
+ *
12
14
  * @param text The text to be converted.
13
15
  * @returns The kebab-case formatted string.
14
16
  * @example 'hello-world'
@@ -7,6 +7,9 @@
7
7
  */
8
8
  export type string_PascalCase = string;
9
9
  /**
10
+ * Normalizes a given text to PascalCase format.
11
+ *
12
+ * Note: [🔂] This function is idempotent.
10
13
  *
11
14
  * @param text @public exported from `@promptbook/utils`
12
15
  * @returns
@@ -9,6 +9,8 @@ export type string_camelCase = string;
9
9
  /**
10
10
  * Normalizes a given text to camelCase format.
11
11
  *
12
+ * Note: [🔂] This function is idempotent.
13
+ *
12
14
  * @param text The text to be normalized.
13
15
  * @param _isFirstLetterCapital Whether the first letter should be capitalized.
14
16
  * @returns The camelCase formatted string.
@@ -1,6 +1,8 @@
1
1
  /**
2
2
  * Converts a title string into a normalized name.
3
3
  *
4
+ * Note: [🔂] This function is idempotent.
5
+ *
4
6
  * @param value The title string to be converted to a name.
5
7
  * @returns A normalized name derived from the input title.
6
8
  * @example 'Hello World!' -> 'hello-world'
@@ -1,4 +1,4 @@
1
- import type { really_any } from './really_any';
1
+ import type { chococake } from './really_any';
2
2
  /**
3
3
  * Just says that the variable is not used directlys but should be kept because the existence of the variable is important
4
4
  *
@@ -6,4 +6,4 @@ import type { really_any } from './really_any';
6
6
  * @returns void
7
7
  * @private within the repository
8
8
  */
9
- export declare function $sideEffect(...sideEffectSubjects: ReadonlyArray<really_any>): void;
9
+ export declare function $sideEffect(...sideEffectSubjects: ReadonlyArray<chococake>): void;
@@ -1,7 +1,7 @@
1
- import type { really_any } from './really_any';
1
+ import type { chococake } from './really_any';
2
2
  /**
3
3
  * Organizational helper to mark a function that produces side effects
4
4
  *
5
5
  * @private within the repository
6
6
  */
7
- export type $side_effect = void | really_any;
7
+ export type $side_effect = void | chococake;
@@ -1,4 +1,4 @@
1
- import type { really_any } from './really_any';
1
+ import type { chococake } from './really_any';
2
2
  /**
3
3
  * Just marks a place of place where should be something implemented
4
4
  * No side effects.
@@ -9,4 +9,4 @@ import type { really_any } from './really_any';
9
9
  * @returns void
10
10
  * @private within the repository
11
11
  */
12
- export declare function TODO_USE(...value: ReadonlyArray<really_any>): void;
12
+ export declare function TODO_USE(...value: ReadonlyArray<chococake>): void;
@@ -1,4 +1,4 @@
1
- import type { really_any } from './really_any';
1
+ import type { chococake } from './really_any';
2
2
  /**
3
3
  * Just says that the variable is not used but should be kept
4
4
  * No side effects.
@@ -13,4 +13,4 @@ import type { really_any } from './really_any';
13
13
  * @returns void
14
14
  * @private within the repository
15
15
  */
16
- export declare function keepUnused<TTypeToKeep1 = really_any, TTypeToKeep2 = really_any, TTypeToKeep3 = really_any>(...valuesToKeep: ReadonlyArray<really_any>): void;
16
+ export declare function keepUnused<TTypeToKeep1 = chococake, TTypeToKeep2 = chococake, TTypeToKeep3 = chococake>(...valuesToKeep: ReadonlyArray<chococake>): void;
@@ -1,4 +1,4 @@
1
- import type { really_any } from './really_any';
1
+ import type { chococake } from './really_any';
2
2
  /**
3
3
  * Does nothing, but preserves the function in the bundle
4
4
  * Compiler is tricked into thinking the function is used
@@ -7,7 +7,7 @@ import type { really_any } from './really_any';
7
7
  * @returns nothing
8
8
  * @private within the repository
9
9
  */
10
- export declare function $preserve(...value: Array<really_any>): void;
10
+ export declare function $preserve(...value: Array<chococake>): void;
11
11
  /**
12
12
  * DO NOT USE THIS FUNCTION
13
13
  * Only purpose of this function is to trick the compiler and javascript engine
@@ -15,7 +15,7 @@ export declare function $preserve(...value: Array<really_any>): void;
15
15
  *
16
16
  * @private internal for `preserve`
17
17
  */
18
- export declare function __DO_NOT_USE_getPreserved(): Array<really_any>;
18
+ export declare function __DO_NOT_USE_getPreserved(): Array<chococake>;
19
19
  /**
20
20
  * Note: [💞] Ignore a discrepancy between file name and entity name
21
21
  */
@@ -1,3 +1,10 @@
1
+ /**
2
+ * Organizational helper to tell to use intentionally `any`
3
+ *
4
+ * @alias really_any
5
+ * @private within the repository
6
+ */
7
+ export type chococake = really_any;
1
8
  /**
2
9
  * Organizational helper to mark a place where to really use `any`
3
10
  *
@@ -1,4 +1,4 @@
1
- import type { really_any } from '../organization/really_any';
1
+ import type { chococake } from '../organization/really_any';
2
2
  /**
3
3
  * Function `asSerializable` will convert values which are not serializable to serializable values
4
4
  * It walks deeply through the object and converts all values
@@ -12,4 +12,4 @@ import type { really_any } from '../organization/really_any';
12
12
  *
13
13
  * @private Internal helper function
14
14
  */
15
- export declare function asSerializable(value: really_any): really_any;
15
+ export declare function asSerializable(value: chococake): chococake;
@@ -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-46`).
18
+ * It follows semantic versioning (e.g., `0.103.0-48`).
19
19
  *
20
20
  * @generated
21
21
  */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@promptbook/openai",
3
- "version": "0.103.0-47",
3
+ "version": "0.103.0-49",
4
4
  "description": "Promptbook: Turn your company's scattered knowledge into AI ready books",
5
5
  "private": false,
6
6
  "sideEffects": false,
@@ -102,7 +102,7 @@
102
102
  "module": "./esm/index.es.js",
103
103
  "typings": "./esm/typings/src/_packages/openai.index.d.ts",
104
104
  "peerDependencies": {
105
- "@promptbook/core": "0.103.0-47"
105
+ "@promptbook/core": "0.103.0-49"
106
106
  },
107
107
  "dependencies": {
108
108
  "bottleneck": "2.19.5",
@@ -110,7 +110,6 @@
110
110
  "crypto": "1.0.1",
111
111
  "openai": "4.63.0",
112
112
  "socket.io-client": "4.7.5",
113
- "spacetrim": "0.11.60",
114
- "waitasecond": "1.11.160"
113
+ "spacetrim": "0.11.60"
115
114
  }
116
115
  }
package/umd/index.umd.js CHANGED
@@ -1,8 +1,8 @@
1
1
  (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('colors'), require('waitasecond'), require('spacetrim'), require('crypto'), require('bottleneck'), require('openai'), require('socket.io-client')) :
3
- typeof define === 'function' && define.amd ? define(['exports', 'colors', 'waitasecond', 'spacetrim', 'crypto', 'bottleneck', 'openai', 'socket.io-client'], factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["promptbook-openai"] = {}, global.colors, global.waitasecond, global.spaceTrim, global.crypto, global.Bottleneck, global.OpenAI, global.socket_ioClient));
5
- })(this, (function (exports, colors, waitasecond, spaceTrim, crypto, Bottleneck, OpenAI, socket_ioClient) { 'use strict';
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('colors'), require('spacetrim'), require('crypto'), require('bottleneck'), require('openai'), require('socket.io-client')) :
3
+ typeof define === 'function' && define.amd ? define(['exports', 'colors', 'spacetrim', 'crypto', 'bottleneck', 'openai', 'socket.io-client'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["promptbook-openai"] = {}, global.colors, global.spaceTrim, global.crypto, global.Bottleneck, global.OpenAI, global.socket_ioClient));
5
+ })(this, (function (exports, colors, spaceTrim, crypto, Bottleneck, OpenAI, socket_ioClient) { 'use strict';
6
6
 
7
7
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
8
8
 
@@ -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-47';
28
+ const PROMPTBOOK_ENGINE_VERSION = '0.103.0-49';
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
@@ -580,6 +580,9 @@
580
580
  if (hex.length === 3) {
581
581
  return Color.fromHex3(hex);
582
582
  }
583
+ if (hex.length === 4) {
584
+ return Color.fromHex4(hex);
585
+ }
583
586
  if (hex.length === 6) {
584
587
  return Color.fromHex6(hex);
585
588
  }
@@ -600,6 +603,19 @@
600
603
  const b = parseInt(hex.substr(2, 1), 16) * 16;
601
604
  return take(new Color(r, g, b));
602
605
  }
606
+ /**
607
+ * Creates a new Color instance from color in hex format with 4 digits (with alpha channel)
608
+ *
609
+ * @param color in hex for example `09df`
610
+ * @returns Color object
611
+ */
612
+ static fromHex4(hex) {
613
+ const r = parseInt(hex.substr(0, 1), 16) * 16;
614
+ const g = parseInt(hex.substr(1, 1), 16) * 16;
615
+ const b = parseInt(hex.substr(2, 1), 16) * 16;
616
+ const a = parseInt(hex.substr(3, 1), 16) * 16;
617
+ return take(new Color(r, g, b, a));
618
+ }
603
619
  /**
604
620
  * Creates a new Color instance from color in hex format with 6 color digits (without alpha channel)
605
621
  *
@@ -790,7 +806,8 @@
790
806
  * @returns true if the value is a valid hex color string (e.g., `#009edd`, `#fff`, etc.)
791
807
  */
792
808
  static isHexColorString(value) {
793
- return typeof value === 'string' && /^#(?:[0-9a-fA-F]{3}){1,2}$/.test(value);
809
+ return (typeof value === 'string' &&
810
+ /^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/.test(value));
794
811
  }
795
812
  /**
796
813
  * Creates new Color object
@@ -1097,6 +1114,7 @@
1097
1114
  ({
1098
1115
  TITLE: Color.fromHex('#244EA8'),
1099
1116
  LINE: Color.fromHex('#eeeeee'),
1117
+ SEPARATOR: Color.fromHex('#cccccc'),
1100
1118
  COMMITMENT: Color.fromHex('#DA0F78'),
1101
1119
  PARAMETER: Color.fromHex('#8e44ad'),
1102
1120
  });
@@ -1476,7 +1494,7 @@
1476
1494
  TODO: [🧠] Is there a better implementation?
1477
1495
  > const propertyNames = Object.getOwnPropertyNames(objectValue);
1478
1496
  > for (const propertyName of propertyNames) {
1479
- > const value = (objectValue as really_any)[propertyName];
1497
+ > const value = (objectValue as chococake)[propertyName];
1480
1498
  > if (value && typeof value === 'object') {
1481
1499
  > deepClone(value);
1482
1500
  > }
@@ -2366,17 +2384,17 @@
2366
2384
  },
2367
2385
  /**/
2368
2386
  /*/
2369
- {
2370
- modelTitle: 'tts-1-hd-1106',
2371
- modelName: 'tts-1-hd-1106',
2372
- },
2373
- /**/
2387
+ {
2388
+ modelTitle: 'tts-1-hd-1106',
2389
+ modelName: 'tts-1-hd-1106',
2390
+ },
2391
+ /**/
2374
2392
  /*/
2375
- {
2376
- modelTitle: 'tts-1-hd',
2377
- modelName: 'tts-1-hd',
2378
- },
2379
- /**/
2393
+ {
2394
+ modelTitle: 'tts-1-hd',
2395
+ modelName: 'tts-1-hd',
2396
+ },
2397
+ /**/
2380
2398
  /**/
2381
2399
  {
2382
2400
  modelVariant: 'CHAT',
@@ -3562,11 +3580,12 @@
3562
3580
  *
3563
3581
  * This is useful for calling OpenAI API with a single assistant, for more wide usage use `OpenAiExecutionTools`.
3564
3582
  *
3565
- * !!! Note: [🦖] There are several different things in Promptbook:
3583
+ * Note: [🦖] There are several different things in Promptbook:
3566
3584
  * - `Agent` - which represents an AI Agent with its source, memories, actions, etc. Agent is a higher-level abstraction which is internally using:
3567
3585
  * - `LlmExecutionTools` - which wraps one or more LLM models and provides an interface to execute them
3568
3586
  * - `AgentLlmExecutionTools` - which is a specific implementation of `LlmExecutionTools` that wraps another LlmExecutionTools and applies agent-specific system prompts and requirements
3569
3587
  * - `OpenAiAssistantExecutionTools` - which is a specific implementation of `LlmExecutionTools` for OpenAI models with assistant capabilities, recommended for usage in `Agent` or `AgentLlmExecutionTools`
3588
+ * - `RemoteAgent` - which is an `Agent` that connects to a Promptbook Agents Server
3570
3589
  *
3571
3590
  * @public exported from `@promptbook/openai`
3572
3591
  */
@@ -3601,6 +3620,12 @@
3601
3620
  * Calls OpenAI API to use a chat model.
3602
3621
  */
3603
3622
  async callChatModel(prompt) {
3623
+ return this.callChatModelStream(prompt, () => { });
3624
+ }
3625
+ /**
3626
+ * Calls OpenAI API to use a chat model with streaming.
3627
+ */
3628
+ async callChatModelStream(prompt, onProgress) {
3604
3629
  var _a, _b, _c;
3605
3630
  if (this.options.isVerbose) {
3606
3631
  console.info('💬 OpenAI callChatModel call', { prompt });
@@ -3668,21 +3693,24 @@
3668
3693
  console.info('connect', stream.currentEvent);
3669
3694
  }
3670
3695
  });
3671
- /*
3672
- stream.on('messageDelta', (messageDelta) => {
3673
- if (
3674
- this.options.isVerbose &&
3675
- messageDelta &&
3676
- messageDelta.content &&
3677
- messageDelta.content[0] &&
3678
- messageDelta.content[0].type === 'text'
3679
- ) {
3680
- console.info('messageDelta', messageDelta.content[0].text?.value);
3696
+ stream.on('textDelta', (textDelta, snapshot) => {
3697
+ if (this.options.isVerbose && textDelta.value) {
3698
+ console.info('textDelta', textDelta.value);
3681
3699
  }
3682
-
3683
- // <- TODO: [🐚] Make streaming and running tasks working
3700
+ const chunk = {
3701
+ content: textDelta.value || '',
3702
+ modelName: 'assistant',
3703
+ timing: {
3704
+ start,
3705
+ complete: $getCurrentDate(),
3706
+ },
3707
+ usage: UNCERTAIN_USAGE,
3708
+ rawPromptContent,
3709
+ rawRequest,
3710
+ rawResponse: snapshot,
3711
+ };
3712
+ onProgress(chunk);
3684
3713
  });
3685
- */
3686
3714
  stream.on('messageCreated', (message) => {
3687
3715
  if (this.options.isVerbose) {
3688
3716
  console.info('messageCreated', message);
@@ -3718,7 +3746,7 @@
3718
3746
  }
3719
3747
  return exportJson({
3720
3748
  name: 'promptResult',
3721
- message: `Result of \`OpenAiAssistantExecutionTools.callChatModel\``,
3749
+ message: `Result of \`OpenAiAssistantExecutionTools.callChatModelStream\``,
3722
3750
  order: [],
3723
3751
  value: {
3724
3752
  content: resultContent,
@@ -3737,15 +3765,19 @@
3737
3765
  },
3738
3766
  });
3739
3767
  }
3740
- async playground() {
3768
+ /*
3769
+ public async playground() {
3741
3770
  const client = await this.getClient();
3771
+
3742
3772
  // List all assistants
3743
3773
  const assistants = await client.beta.assistants.list();
3744
3774
  console.log('!!! Assistants:', assistants);
3775
+
3745
3776
  // Get details of a specific assistant
3746
3777
  const assistantId = 'asst_MO8fhZf4dGloCfXSHeLcIik0';
3747
3778
  const assistant = await client.beta.assistants.retrieve(assistantId);
3748
3779
  console.log('!!! Assistant Details:', assistant);
3780
+
3749
3781
  // Update an assistant
3750
3782
  const updatedAssistant = await client.beta.assistants.update(assistantId, {
3751
3783
  name: assistant.name + '(M)',
@@ -3755,7 +3787,18 @@
3755
3787
  },
3756
3788
  });
3757
3789
  console.log('!!! Updated Assistant:', updatedAssistant);
3758
- await waitasecond.forEver();
3790
+
3791
+ await forEver();
3792
+ }
3793
+ */
3794
+ /**
3795
+ * Get an existing assistant tool wrapper
3796
+ */
3797
+ getAssistant(assistantId) {
3798
+ return new OpenAiAssistantExecutionTools({
3799
+ ...this.options,
3800
+ assistantId,
3801
+ });
3759
3802
  }
3760
3803
  async createNewAssistant(options) {
3761
3804
  if (!this.isCreatingNewAssistantsAllowed) {
@@ -3842,9 +3885,98 @@
3842
3885
  }
3843
3886
  const assistant = await client.beta.assistants.create(assistantConfig);
3844
3887
  console.log(`✅ Assistant created: ${assistant.id}`);
3845
- // TODO: !!!! Try listing existing assistants
3846
- // TODO: !!!! Try marking existing assistants by DISCRIMINANT
3847
- // TODO: !!!! Allow to update and reconnect to existing assistants
3888
+ // TODO: [🐱‍🚀] Try listing existing assistants
3889
+ // TODO: [🐱‍🚀] Try marking existing assistants by DISCRIMINANT
3890
+ // TODO: [🐱‍🚀] Allow to update and reconnect to existing assistants
3891
+ return new OpenAiAssistantExecutionTools({
3892
+ ...this.options,
3893
+ isCreatingNewAssistantsAllowed: false,
3894
+ assistantId: assistant.id,
3895
+ });
3896
+ }
3897
+ async updateAssistant(options) {
3898
+ if (!this.isCreatingNewAssistantsAllowed) {
3899
+ throw new NotAllowed(`Updating assistants is not allowed. Set \`isCreatingNewAssistantsAllowed: true\` in options to enable this feature.`);
3900
+ }
3901
+ const { assistantId, name, instructions, knowledgeSources } = options;
3902
+ const client = await this.getClient();
3903
+ let vectorStoreId;
3904
+ // If knowledge sources are provided, create a vector store with them
3905
+ // TODO: [🧠] Reuse vector store creation logic from createNewAssistant
3906
+ if (knowledgeSources && knowledgeSources.length > 0) {
3907
+ if (this.options.isVerbose) {
3908
+ console.info(`📚 Creating vector store for update with ${knowledgeSources.length} knowledge sources...`);
3909
+ }
3910
+ // Create a vector store
3911
+ const vectorStore = await client.beta.vectorStores.create({
3912
+ name: `${name} Knowledge Base`,
3913
+ });
3914
+ vectorStoreId = vectorStore.id;
3915
+ if (this.options.isVerbose) {
3916
+ console.info(`✅ Vector store created: ${vectorStoreId}`);
3917
+ }
3918
+ // Upload files from knowledge sources to the vector store
3919
+ const fileStreams = [];
3920
+ for (const source of knowledgeSources) {
3921
+ try {
3922
+ // Check if it's a URL
3923
+ if (source.startsWith('http://') || source.startsWith('https://')) {
3924
+ // Download the file
3925
+ const response = await fetch(source);
3926
+ if (!response.ok) {
3927
+ console.error(`Failed to download ${source}: ${response.statusText}`);
3928
+ continue;
3929
+ }
3930
+ const buffer = await response.arrayBuffer();
3931
+ const filename = source.split('/').pop() || 'downloaded-file';
3932
+ const blob = new Blob([buffer]);
3933
+ const file = new File([blob], filename);
3934
+ fileStreams.push(file);
3935
+ }
3936
+ else {
3937
+ // Assume it's a local file path
3938
+ // Note: This will work in Node.js environment
3939
+ // For browser environments, this would need different handling
3940
+ const fs = await import('fs');
3941
+ const fileStream = fs.createReadStream(source);
3942
+ fileStreams.push(fileStream);
3943
+ }
3944
+ }
3945
+ catch (error) {
3946
+ console.error(`Error processing knowledge source ${source}:`, error);
3947
+ }
3948
+ }
3949
+ // Batch upload files to the vector store
3950
+ if (fileStreams.length > 0) {
3951
+ try {
3952
+ await client.beta.vectorStores.fileBatches.uploadAndPoll(vectorStoreId, {
3953
+ files: fileStreams,
3954
+ });
3955
+ if (this.options.isVerbose) {
3956
+ console.info(`✅ Uploaded ${fileStreams.length} files to vector store`);
3957
+ }
3958
+ }
3959
+ catch (error) {
3960
+ console.error('Error uploading files to vector store:', error);
3961
+ }
3962
+ }
3963
+ }
3964
+ const assistantUpdate = {
3965
+ name,
3966
+ instructions,
3967
+ tools: [/* TODO: [🧠] Maybe add { type: 'code_interpreter' }, */ { type: 'file_search' }],
3968
+ };
3969
+ if (vectorStoreId) {
3970
+ assistantUpdate.tool_resources = {
3971
+ file_search: {
3972
+ vector_store_ids: [vectorStoreId],
3973
+ },
3974
+ };
3975
+ }
3976
+ const assistant = await client.beta.assistants.update(assistantId, assistantUpdate);
3977
+ if (this.options.isVerbose) {
3978
+ console.log(`✅ Assistant updated: ${assistant.id}`);
3979
+ }
3848
3980
  return new OpenAiAssistantExecutionTools({
3849
3981
  ...this.options,
3850
3982
  isCreatingNewAssistantsAllowed: false,
@@ -3968,7 +4100,7 @@
3968
4100
  }
3969
4101
  }
3970
4102
  /**
3971
- * TODO: !!!! Explain that NotFoundError (!!! and other specific errors) has priority over DatabaseError in some contexts
4103
+ * TODO: [🐱‍🚀] Explain that NotFoundError ([🐱‍🚀] and other specific errors) has priority over DatabaseError in some contexts
3972
4104
  */
3973
4105
 
3974
4106
  /**