@agentica/core 0.8.3 → 0.9.0-dev.20250302

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 (91) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +419 -404
  3. package/lib/Agentica.d.ts +10 -9
  4. package/lib/Agentica.js.map +1 -1
  5. package/lib/chatgpt/ChatGptAgent.d.ts +2 -1
  6. package/lib/chatgpt/ChatGptAgent.js.map +1 -1
  7. package/lib/chatgpt/ChatGptCallFunctionAgent.d.ts +2 -1
  8. package/lib/chatgpt/ChatGptCallFunctionAgent.js +3 -1
  9. package/lib/chatgpt/ChatGptCallFunctionAgent.js.map +1 -1
  10. package/lib/chatgpt/ChatGptCancelFunctionAgent.d.ts +3 -2
  11. package/lib/chatgpt/ChatGptCancelFunctionAgent.js +55 -2
  12. package/lib/chatgpt/ChatGptCancelFunctionAgent.js.map +1 -1
  13. package/lib/chatgpt/ChatGptDescribeFunctionAgent.d.ts +2 -1
  14. package/lib/chatgpt/ChatGptDescribeFunctionAgent.js.map +1 -1
  15. package/lib/chatgpt/ChatGptHistoryDecoder.d.ts +2 -1
  16. package/lib/chatgpt/ChatGptHistoryDecoder.js.map +1 -1
  17. package/lib/chatgpt/ChatGptInitializeFunctionAgent.d.ts +2 -1
  18. package/lib/chatgpt/ChatGptInitializeFunctionAgent.js +63 -1
  19. package/lib/chatgpt/ChatGptInitializeFunctionAgent.js.map +1 -1
  20. package/lib/chatgpt/ChatGptSelectFunctionAgent.d.ts +2 -1
  21. package/lib/chatgpt/ChatGptSelectFunctionAgent.js +55 -2
  22. package/lib/chatgpt/ChatGptSelectFunctionAgent.js.map +1 -1
  23. package/lib/functional/createHttpLlmApplication.js +826 -798
  24. package/lib/functional/createHttpLlmApplication.js.map +1 -1
  25. package/lib/index.mjs +987 -804
  26. package/lib/index.mjs.map +1 -1
  27. package/lib/internal/AgenticaDefaultPrompt.d.ts +2 -1
  28. package/lib/internal/AgenticaDefaultPrompt.js.map +1 -1
  29. package/lib/internal/AgenticaOperationComposer.d.ts +5 -4
  30. package/lib/internal/AgenticaOperationComposer.js +1 -1
  31. package/lib/internal/AgenticaOperationComposer.js.map +1 -1
  32. package/lib/internal/AgenticaPromptFactory.d.ts +3 -2
  33. package/lib/internal/AgenticaPromptFactory.js.map +1 -1
  34. package/lib/internal/AgenticaPromptTransformer.d.ts +5 -4
  35. package/lib/internal/AgenticaPromptTransformer.js.map +1 -1
  36. package/lib/structures/IAgenticaConfig.d.ts +4 -3
  37. package/lib/structures/IAgenticaContext.d.ts +7 -6
  38. package/lib/structures/IAgenticaController.d.ts +8 -8
  39. package/lib/structures/IAgenticaEvent.d.ts +19 -18
  40. package/lib/structures/IAgenticaExecutor.d.ts +7 -6
  41. package/lib/structures/IAgenticaOperation.d.ts +4 -4
  42. package/lib/structures/IAgenticaOperationCollection.d.ts +6 -5
  43. package/lib/structures/IAgenticaOperationSelection.d.ts +4 -4
  44. package/lib/structures/IAgenticaPrompt.d.ts +11 -11
  45. package/lib/structures/IAgenticaProps.d.ts +9 -4
  46. package/lib/structures/IAgenticaProvider.d.ts +22 -27
  47. package/lib/structures/IAgenticaSystemPrompt.d.ts +8 -7
  48. package/package.json +6 -9
  49. package/prompts/cancel.md +4 -4
  50. package/prompts/common.md +2 -2
  51. package/prompts/describe.md +6 -6
  52. package/prompts/execute.md +6 -6
  53. package/prompts/initialize.md +2 -2
  54. package/prompts/select.md +6 -6
  55. package/src/Agentica.ts +323 -318
  56. package/src/chatgpt/ChatGptAgent.ts +75 -71
  57. package/src/chatgpt/ChatGptCallFunctionAgent.ts +448 -445
  58. package/src/chatgpt/ChatGptCancelFunctionAgent.ts +287 -283
  59. package/src/chatgpt/ChatGptDescribeFunctionAgent.ts +52 -51
  60. package/src/chatgpt/ChatGptHistoryDecoder.ts +88 -87
  61. package/src/chatgpt/ChatGptInitializeFunctionAgent.ts +88 -88
  62. package/src/chatgpt/ChatGptSelectFunctionAgent.ts +319 -318
  63. package/src/functional/createHttpLlmApplication.ts +63 -63
  64. package/src/index.ts +19 -19
  65. package/src/internal/AgenticaConstant.ts +4 -4
  66. package/src/internal/AgenticaDefaultPrompt.ts +43 -39
  67. package/src/internal/AgenticaOperationComposer.ts +87 -82
  68. package/src/internal/AgenticaPromptFactory.ts +32 -30
  69. package/src/internal/AgenticaPromptTransformer.ts +86 -83
  70. package/src/internal/AgenticaTokenUsageAggregator.ts +115 -115
  71. package/src/internal/MathUtil.ts +3 -3
  72. package/src/internal/Singleton.ts +22 -22
  73. package/src/internal/__map_take.ts +15 -15
  74. package/src/structures/IAgenticaConfig.ts +123 -121
  75. package/src/structures/IAgenticaContext.ts +129 -128
  76. package/src/structures/IAgenticaController.ts +132 -130
  77. package/src/structures/IAgenticaEvent.ts +229 -224
  78. package/src/structures/IAgenticaExecutor.ts +156 -152
  79. package/src/structures/IAgenticaOperation.ts +64 -64
  80. package/src/structures/IAgenticaOperationCollection.ts +52 -50
  81. package/src/structures/IAgenticaOperationSelection.ts +69 -69
  82. package/src/structures/IAgenticaPrompt.ts +178 -173
  83. package/src/structures/IAgenticaProps.ts +70 -64
  84. package/src/structures/IAgenticaProvider.ts +39 -45
  85. package/src/structures/IAgenticaSystemPrompt.ts +124 -122
  86. package/src/structures/IAgenticaTokenUsage.ts +107 -107
  87. package/src/structures/internal/__IChatCancelFunctionsApplication.ts +23 -23
  88. package/src/structures/internal/__IChatFunctionReference.ts +21 -21
  89. package/src/structures/internal/__IChatInitialApplication.ts +15 -15
  90. package/src/structures/internal/__IChatSelectFunctionsApplication.ts +24 -24
  91. package/src/typings/AgenticaSource.ts +6 -6
package/src/Agentica.ts CHANGED
@@ -1,318 +1,323 @@
1
- import OpenAI from "openai";
2
-
3
- import { ChatGptAgent } from "./chatgpt/ChatGptAgent";
4
- import { AgenticaOperationComposer } from "./internal/AgenticaOperationComposer";
5
- import { AgenticaPromptTransformer } from "./internal/AgenticaPromptTransformer";
6
- import { AgenticaTokenUsageAggregator } from "./internal/AgenticaTokenUsageAggregator";
7
- import { __map_take } from "./internal/__map_take";
8
- import { IAgenticaConfig } from "./structures/IAgenticaConfig";
9
- import { IAgenticaContext } from "./structures/IAgenticaContext";
10
- import { IAgenticaController } from "./structures/IAgenticaController";
11
- import { IAgenticaEvent } from "./structures/IAgenticaEvent";
12
- import { IAgenticaOperation } from "./structures/IAgenticaOperation";
13
- import { IAgenticaOperationCollection } from "./structures/IAgenticaOperationCollection";
14
- import { IAgenticaOperationSelection } from "./structures/IAgenticaOperationSelection";
15
- import { IAgenticaPrompt } from "./structures/IAgenticaPrompt";
16
- import { IAgenticaProps } from "./structures/IAgenticaProps";
17
- import { IAgenticaProvider } from "./structures/IAgenticaProvider";
18
- import { IAgenticaTokenUsage } from "./structures/IAgenticaTokenUsage";
19
-
20
- /**
21
- * Nestia A.I. chatbot agent.
22
- *
23
- * `Agentica` is a facade class for the super A.I. chatbot agent
24
- * which performs the {@link conversate user's conversation function}
25
- * with LLM (Large Language Model) function calling and manages the
26
- * {@link getPromptHistories prompt histories}.
27
- *
28
- * To understand and compose the `Agentica` class exactly, reference
29
- * below types concentrating on the documentation comments please.
30
- * Especially, you have to be careful about the {@link IAgenticaProps}
31
- * type which is used in the {@link constructor} function.
32
- *
33
- * - Constructors
34
- * - {@link IAgenticaProps}
35
- * - {@link IAgenticaProvider}
36
- * - {@link IAgenticaController}
37
- * - {@link IAgenticaConfig}
38
- * - {@link IAgenticaSystemPrompt}
39
- * - Accessors
40
- * - {@link IAgenticaOperation}
41
- * - {@link IAgenticaPrompt}
42
- * - {@link IAgenticaEvent}
43
- * - {@link IAgenticaTokenUsage}
44
- *
45
- * @author Samchon
46
- */
47
- export class Agentica {
48
- // THE OPERATIONS
49
- private readonly operations_: IAgenticaOperationCollection;
50
-
51
- // STACK
52
- private readonly stack_: IAgenticaOperationSelection[];
53
- private readonly prompt_histories_: IAgenticaPrompt[];
54
- private readonly listeners_: Map<string, Set<Function>>;
55
-
56
- // STATUS
57
- private readonly token_usage_: IAgenticaTokenUsage;
58
- private ready_: boolean;
59
- private readonly executor_: (
60
- ctx: IAgenticaContext,
61
- ) => Promise<IAgenticaPrompt[]>;
62
-
63
- /* -----------------------------------------------------------
64
- CONSTRUCTOR
65
- ----------------------------------------------------------- */
66
- /**
67
- * Initializer constructor.
68
- *
69
- * @param props Properties to construct the agent
70
- */
71
- public constructor(private readonly props: IAgenticaProps) {
72
- // OPERATIONS
73
- this.operations_ = AgenticaOperationComposer.compose({
74
- controllers: props.controllers,
75
- config: props.config,
76
- });
77
-
78
- // STATUS
79
- this.stack_ = [];
80
- this.listeners_ = new Map();
81
- this.prompt_histories_ = (props.histories ?? []).map((input) =>
82
- AgenticaPromptTransformer.transform({
83
- operations: this.operations_.group,
84
- input,
85
- }),
86
- );
87
-
88
- // STATUS
89
- this.token_usage_ = AgenticaTokenUsageAggregator.zero();
90
- this.ready_ = false;
91
- this.executor_ =
92
- typeof props.config?.executor === "function"
93
- ? props.config.executor
94
- : ChatGptAgent.execute(props.config?.executor ?? null);
95
- }
96
-
97
- /**
98
- * @internal
99
- */
100
- public clone(): Agentica {
101
- return new Agentica({
102
- ...this.props,
103
- histories: this.props.histories?.slice(),
104
- });
105
- }
106
-
107
- /* -----------------------------------------------------------
108
- ACCESSORS
109
- ----------------------------------------------------------- */
110
- /**
111
- * Conversate with the A.I. chatbot.
112
- *
113
- * User talks to the A.I. chatbot with the content.
114
- *
115
- * When the user's conversation implies the A.I. chatbot to execute a
116
- * function calling, the returned chat prompts will contain the
117
- * function calling information like {@link IAgenticaPrompt.IExecute}.
118
- *
119
- * @param content The content to talk
120
- * @returns List of newly created chat prompts
121
- */
122
- public async conversate(content: string): Promise<IAgenticaPrompt[]> {
123
- const prompt: IAgenticaPrompt.IText<"user"> = {
124
- type: "text",
125
- role: "user",
126
- text: content,
127
- };
128
- await this.dispatch(prompt);
129
-
130
- const newbie: IAgenticaPrompt[] = await this.executor_(
131
- this.getContext({
132
- prompt,
133
- usage: this.token_usage_,
134
- }),
135
- );
136
- this.prompt_histories_.push(prompt, ...newbie);
137
- return [prompt, ...newbie];
138
- }
139
-
140
- /**
141
- * Get configuration.
142
- */
143
- public getConfig(): IAgenticaConfig | undefined {
144
- return this.props.config;
145
- }
146
-
147
- /**
148
- * Get LLM Provider.
149
- */
150
- public getProvider(): IAgenticaProvider {
151
- return this.props.provider;
152
- }
153
-
154
- /**
155
- * Get controllers.
156
- *
157
- * Get list of controllers, which are the collection of functions that
158
- * the "Super A.I. Chatbot" can execute.
159
- */
160
- public getControllers(): ReadonlyArray<IAgenticaController> {
161
- return this.props.controllers;
162
- }
163
-
164
- /**
165
- * Get operations.
166
- *
167
- * Get list of operations, which has capsuled the pair of controller
168
- * and function from the {@link getControllers controllers}.
169
- *
170
- * @returns
171
- */
172
- public getOperations(): ReadonlyArray<IAgenticaOperation> {
173
- return this.operations_.array;
174
- }
175
-
176
- /**
177
- * Get the chatbot's prompt histories.
178
- *
179
- * Get list of chat prompts that the chatbot has been conversated.
180
- *
181
- * @returns List of chat prompts
182
- */
183
- public getPromptHistories(): IAgenticaPrompt[] {
184
- return this.prompt_histories_;
185
- }
186
-
187
- /**
188
- * Get token usage of the A.I. chatbot.
189
- *
190
- * Entire token usage of the A.I. chatbot during the conversating
191
- * with the user by {@link conversate} method callings.
192
- *
193
- * @returns Cost of the A.I. chatbot
194
- */
195
- public getTokenUsage(): IAgenticaTokenUsage {
196
- return this.token_usage_;
197
- }
198
-
199
- /**
200
- * @internal
201
- */
202
- public getContext(props: {
203
- prompt: IAgenticaPrompt.IText<"user">;
204
- usage: IAgenticaTokenUsage;
205
- }): IAgenticaContext {
206
- const dispatch = (event: IAgenticaEvent) => this.dispatch(event);
207
- return {
208
- // APPLICATION
209
- operations: this.operations_,
210
- config: this.props.config,
211
-
212
- // STATES
213
- histories: this.prompt_histories_,
214
- stack: this.stack_,
215
- ready: () => this.ready_,
216
- prompt: props.prompt,
217
-
218
- // HANDLERS
219
- dispatch: (event) => this.dispatch(event),
220
- request: async (kind, body) => {
221
- // request information
222
- const event: IAgenticaEvent.IRequest = {
223
- type: "request",
224
- source: kind,
225
- body: {
226
- ...body,
227
- model: this.props.provider.model,
228
- },
229
- options: this.props.provider.options,
230
- };
231
- await dispatch(event);
232
-
233
- // completion
234
- const completion: OpenAI.ChatCompletion =
235
- await this.props.provider.api.chat.completions.create(
236
- event.body,
237
- event.options,
238
- );
239
- AgenticaTokenUsageAggregator.aggregate({
240
- kind,
241
- completion,
242
- usage: props.usage,
243
- });
244
- await dispatch({
245
- type: "response",
246
- source: kind,
247
- body: event.body,
248
- options: event.options,
249
- value: completion,
250
- });
251
- return completion;
252
- },
253
- initialize: async () => {
254
- this.ready_ = true;
255
- await dispatch({
256
- type: "initialize",
257
- });
258
- },
259
- };
260
- }
261
-
262
- /* -----------------------------------------------------------
263
- EVENT HANDLERS
264
- ----------------------------------------------------------- */
265
- /**
266
- * Add an event listener.
267
- *
268
- * Add an event listener to be called whenever the event is emitted.
269
- *
270
- * @param type Type of event
271
- * @param listener Callback function to be called whenever the event is emitted
272
- */
273
- public on<Type extends IAgenticaEvent.Type>(
274
- type: Type,
275
- listener: (event: IAgenticaEvent.Mapper[Type]) => void | Promise<void>,
276
- ): this {
277
- __map_take(this.listeners_, type, () => new Set()).add(listener);
278
- return this;
279
- }
280
-
281
- /**
282
- * Erase an event listener.
283
- *
284
- * Erase an event listener to stop calling the callback function.
285
- *
286
- * @param type Type of event
287
- * @param listener Callback function to erase
288
- */
289
- public off<Type extends IAgenticaEvent.Type>(
290
- type: Type,
291
- listener: (event: IAgenticaEvent.Mapper[Type]) => void | Promise<void>,
292
- ): this {
293
- const set = this.listeners_.get(type);
294
- if (set) {
295
- set.delete(listener);
296
- if (set.size === 0) this.listeners_.delete(type);
297
- }
298
- return this;
299
- }
300
-
301
- private async dispatch<Event extends IAgenticaEvent>(
302
- event: Event,
303
- ): Promise<void> {
304
- const set = this.listeners_.get(event.type);
305
- if (set) {
306
- await Promise.all(
307
- Array.from(set).map(async (listener) => {
308
- try {
309
- // eslint-disable-next-line @typescript-eslint/no-unsafe-call
310
- await listener(event);
311
- } catch {
312
- /* empty */
313
- }
314
- }),
315
- );
316
- }
317
- }
318
- }
1
+ import { ILlmSchema } from "@samchon/openapi";
2
+ import OpenAI from "openai";
3
+
4
+ import { ChatGptAgent } from "./chatgpt/ChatGptAgent";
5
+ import { AgenticaOperationComposer } from "./internal/AgenticaOperationComposer";
6
+ import { AgenticaPromptTransformer } from "./internal/AgenticaPromptTransformer";
7
+ import { AgenticaTokenUsageAggregator } from "./internal/AgenticaTokenUsageAggregator";
8
+ import { __map_take } from "./internal/__map_take";
9
+ import { IAgenticaConfig } from "./structures/IAgenticaConfig";
10
+ import { IAgenticaContext } from "./structures/IAgenticaContext";
11
+ import { IAgenticaController } from "./structures/IAgenticaController";
12
+ import { IAgenticaEvent } from "./structures/IAgenticaEvent";
13
+ import { IAgenticaOperation } from "./structures/IAgenticaOperation";
14
+ import { IAgenticaOperationCollection } from "./structures/IAgenticaOperationCollection";
15
+ import { IAgenticaOperationSelection } from "./structures/IAgenticaOperationSelection";
16
+ import { IAgenticaPrompt } from "./structures/IAgenticaPrompt";
17
+ import { IAgenticaProps } from "./structures/IAgenticaProps";
18
+ import { IAgenticaProvider } from "./structures/IAgenticaProvider";
19
+ import { IAgenticaTokenUsage } from "./structures/IAgenticaTokenUsage";
20
+
21
+ /**
22
+ * Nestia A.I. chatbot agent.
23
+ *
24
+ * `Agentica` is a facade class for the super A.I. chatbot agent
25
+ * which performs the {@link conversate user's conversation function}
26
+ * with LLM (Large Language Model) function calling and manages the
27
+ * {@link getPromptHistories prompt histories}.
28
+ *
29
+ * To understand and compose the `Agentica` class exactly, reference
30
+ * below types concentrating on the documentation comments please.
31
+ * Especially, you have to be careful about the {@link IAgenticaProps}
32
+ * type which is used in the {@link constructor} function.
33
+ *
34
+ * - Constructors
35
+ * - {@link IAgenticaProps}
36
+ * - {@link IAgenticaProvider}
37
+ * - {@link IAgenticaController}
38
+ * - {@link IAgenticaConfig}
39
+ * - {@link IAgenticaSystemPrompt}
40
+ * - Accessors
41
+ * - {@link IAgenticaOperation}
42
+ * - {@link IAgenticaPrompt}
43
+ * - {@link IAgenticaEvent}
44
+ * - {@link IAgenticaTokenUsage}
45
+ *
46
+ * @author Samchon
47
+ */
48
+ export class Agentica<Model extends ILlmSchema.Model> {
49
+ // THE OPERATIONS
50
+ private readonly operations_: IAgenticaOperationCollection<Model>;
51
+
52
+ // STACK
53
+ private readonly stack_: IAgenticaOperationSelection<Model>[];
54
+ private readonly prompt_histories_: IAgenticaPrompt<Model>[];
55
+ private readonly listeners_: Map<string, Set<Function>>;
56
+
57
+ // STATUS
58
+ private readonly token_usage_: IAgenticaTokenUsage;
59
+ private ready_: boolean;
60
+ private readonly executor_: (
61
+ ctx: IAgenticaContext<Model>,
62
+ ) => Promise<IAgenticaPrompt<Model>[]>;
63
+
64
+ /* -----------------------------------------------------------
65
+ CONSTRUCTOR
66
+ ----------------------------------------------------------- */
67
+ /**
68
+ * Initializer constructor.
69
+ *
70
+ * @param props Properties to construct the agent
71
+ */
72
+ public constructor(private readonly props: IAgenticaProps<Model>) {
73
+ // OPERATIONS
74
+ this.operations_ = AgenticaOperationComposer.compose({
75
+ controllers: props.controllers,
76
+ config: props.config,
77
+ });
78
+
79
+ // STATUS
80
+ this.stack_ = [];
81
+ this.listeners_ = new Map();
82
+ this.prompt_histories_ = (props.histories ?? []).map((input) =>
83
+ AgenticaPromptTransformer.transform({
84
+ operations: this.operations_.group,
85
+ input,
86
+ }),
87
+ );
88
+
89
+ // STATUS
90
+ this.token_usage_ = AgenticaTokenUsageAggregator.zero();
91
+ this.ready_ = false;
92
+ this.executor_ =
93
+ typeof props.config?.executor === "function"
94
+ ? props.config.executor
95
+ : ChatGptAgent.execute(props.config?.executor ?? null);
96
+ }
97
+
98
+ /**
99
+ * @internal
100
+ */
101
+ public clone(): Agentica<Model> {
102
+ return new Agentica({
103
+ ...this.props,
104
+ histories: this.props.histories?.slice(),
105
+ });
106
+ }
107
+
108
+ /* -----------------------------------------------------------
109
+ ACCESSORS
110
+ ----------------------------------------------------------- */
111
+ /**
112
+ * Conversate with the A.I. chatbot.
113
+ *
114
+ * User talks to the A.I. chatbot with the content.
115
+ *
116
+ * When the user's conversation implies the A.I. chatbot to execute a
117
+ * function calling, the returned chat prompts will contain the
118
+ * function calling information like {@link IAgenticaPrompt.IExecute}.
119
+ *
120
+ * @param content The content to talk
121
+ * @returns List of newly created chat prompts
122
+ */
123
+ public async conversate(content: string): Promise<IAgenticaPrompt<Model>[]> {
124
+ const prompt: IAgenticaPrompt.IText<"user"> = {
125
+ type: "text",
126
+ role: "user",
127
+ text: content,
128
+ };
129
+ await this.dispatch(prompt);
130
+
131
+ const newbie: IAgenticaPrompt<Model>[] = await this.executor_(
132
+ this.getContext({
133
+ prompt,
134
+ usage: this.token_usage_,
135
+ }),
136
+ );
137
+ this.prompt_histories_.push(prompt, ...newbie);
138
+ return [prompt, ...newbie];
139
+ }
140
+
141
+ /**
142
+ * Get configuration.
143
+ */
144
+ public getConfig(): IAgenticaConfig<Model> | undefined {
145
+ return this.props.config;
146
+ }
147
+
148
+ /**
149
+ * Get LLM Provider.
150
+ */
151
+ public getProvider(): IAgenticaProvider {
152
+ return this.props.provider;
153
+ }
154
+
155
+ /**
156
+ * Get controllers.
157
+ *
158
+ * Get list of controllers, which are the collection of functions that
159
+ * the "Super A.I. Chatbot" can execute.
160
+ */
161
+ public getControllers(): ReadonlyArray<IAgenticaController<Model>> {
162
+ return this.props.controllers;
163
+ }
164
+
165
+ /**
166
+ * Get operations.
167
+ *
168
+ * Get list of operations, which has capsuled the pair of controller
169
+ * and function from the {@link getControllers controllers}.
170
+ *
171
+ * @returns
172
+ */
173
+ public getOperations(): ReadonlyArray<IAgenticaOperation<Model>> {
174
+ return this.operations_.array;
175
+ }
176
+
177
+ /**
178
+ * Get the chatbot's prompt histories.
179
+ *
180
+ * Get list of chat prompts that the chatbot has been conversated.
181
+ *
182
+ * @returns List of chat prompts
183
+ */
184
+ public getPromptHistories(): IAgenticaPrompt<Model>[] {
185
+ return this.prompt_histories_;
186
+ }
187
+
188
+ /**
189
+ * Get token usage of the A.I. chatbot.
190
+ *
191
+ * Entire token usage of the A.I. chatbot during the conversating
192
+ * with the user by {@link conversate} method callings.
193
+ *
194
+ * @returns Cost of the A.I. chatbot
195
+ */
196
+ public getTokenUsage(): IAgenticaTokenUsage {
197
+ return this.token_usage_;
198
+ }
199
+
200
+ /**
201
+ * @internal
202
+ */
203
+ public getContext(props: {
204
+ prompt: IAgenticaPrompt.IText<"user">;
205
+ usage: IAgenticaTokenUsage;
206
+ }): IAgenticaContext<Model> {
207
+ const dispatch = (event: IAgenticaEvent<Model>) => this.dispatch(event);
208
+ return {
209
+ // APPLICATION
210
+ operations: this.operations_,
211
+ config: this.props.config,
212
+
213
+ // STATES
214
+ histories: this.prompt_histories_,
215
+ stack: this.stack_,
216
+ ready: () => this.ready_,
217
+ prompt: props.prompt,
218
+
219
+ // HANDLERS
220
+ dispatch: (event) => this.dispatch(event),
221
+ request: async (kind, body) => {
222
+ // request information
223
+ const event: IAgenticaEvent.IRequest = {
224
+ type: "request",
225
+ source: kind,
226
+ body: {
227
+ ...body,
228
+ model: this.props.provider.model,
229
+ },
230
+ options: this.props.provider.options,
231
+ };
232
+ await dispatch(event);
233
+
234
+ // completion
235
+ const completion: OpenAI.ChatCompletion =
236
+ await this.props.provider.api.chat.completions.create(
237
+ event.body,
238
+ event.options,
239
+ );
240
+ AgenticaTokenUsageAggregator.aggregate({
241
+ kind,
242
+ completion,
243
+ usage: props.usage,
244
+ });
245
+ await dispatch({
246
+ type: "response",
247
+ source: kind,
248
+ body: event.body,
249
+ options: event.options,
250
+ value: completion,
251
+ });
252
+ return completion;
253
+ },
254
+ initialize: async () => {
255
+ this.ready_ = true;
256
+ await dispatch({
257
+ type: "initialize",
258
+ });
259
+ },
260
+ };
261
+ }
262
+
263
+ /* -----------------------------------------------------------
264
+ EVENT HANDLERS
265
+ ----------------------------------------------------------- */
266
+ /**
267
+ * Add an event listener.
268
+ *
269
+ * Add an event listener to be called whenever the event is emitted.
270
+ *
271
+ * @param type Type of event
272
+ * @param listener Callback function to be called whenever the event is emitted
273
+ */
274
+ public on<Type extends IAgenticaEvent.Type>(
275
+ type: Type,
276
+ listener: (
277
+ event: IAgenticaEvent.Mapper<Model>[Type],
278
+ ) => void | Promise<void>,
279
+ ): this {
280
+ __map_take(this.listeners_, type, () => new Set()).add(listener);
281
+ return this;
282
+ }
283
+
284
+ /**
285
+ * Erase an event listener.
286
+ *
287
+ * Erase an event listener to stop calling the callback function.
288
+ *
289
+ * @param type Type of event
290
+ * @param listener Callback function to erase
291
+ */
292
+ public off<Type extends IAgenticaEvent.Type>(
293
+ type: Type,
294
+ listener: (
295
+ event: IAgenticaEvent.Mapper<Model>[Type],
296
+ ) => void | Promise<void>,
297
+ ): this {
298
+ const set = this.listeners_.get(type);
299
+ if (set) {
300
+ set.delete(listener);
301
+ if (set.size === 0) this.listeners_.delete(type);
302
+ }
303
+ return this;
304
+ }
305
+
306
+ private async dispatch<Event extends IAgenticaEvent<Model>>(
307
+ event: Event,
308
+ ): Promise<void> {
309
+ const set = this.listeners_.get(event.type);
310
+ if (set) {
311
+ await Promise.all(
312
+ Array.from(set).map(async (listener) => {
313
+ try {
314
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-call
315
+ await listener(event);
316
+ } catch {
317
+ /* empty */
318
+ }
319
+ }),
320
+ );
321
+ }
322
+ }
323
+ }