@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
@@ -1,445 +1,448 @@
1
- import {
2
- ChatGptTypeChecker,
3
- HttpLlm,
4
- IChatGptSchema,
5
- IHttpMigrateRoute,
6
- IHttpResponse,
7
- } from "@samchon/openapi";
8
- import OpenAI from "openai";
9
- import { IValidation } from "typia";
10
-
11
- import { AgenticaConstant } from "../internal/AgenticaConstant";
12
- import { AgenticaDefaultPrompt } from "../internal/AgenticaDefaultPrompt";
13
- import { AgenticaPromptFactory } from "../internal/AgenticaPromptFactory";
14
- import { AgenticaSystemPrompt } from "../internal/AgenticaSystemPrompt";
15
- import { IAgenticaContext } from "../structures/IAgenticaContext";
16
- import { IAgenticaEvent } from "../structures/IAgenticaEvent";
17
- import { IAgenticaOperation } from "../structures/IAgenticaOperation";
18
- import { IAgenticaPrompt } from "../structures/IAgenticaPrompt";
19
- import { ChatGptCancelFunctionAgent } from "./ChatGptCancelFunctionAgent";
20
- import { ChatGptHistoryDecoder } from "./ChatGptHistoryDecoder";
21
-
22
- export namespace ChatGptCallFunctionAgent {
23
- export const execute = async (
24
- ctx: IAgenticaContext,
25
- ): Promise<IAgenticaPrompt[]> => {
26
- //----
27
- // EXECUTE CHATGPT API
28
- //----
29
- const completion: OpenAI.ChatCompletion = await ctx.request("call", {
30
- messages: [
31
- // COMMON SYSTEM PROMPT
32
- {
33
- role: "system",
34
- content: AgenticaDefaultPrompt.write(ctx.config),
35
- } satisfies OpenAI.ChatCompletionSystemMessageParam,
36
- // PREVIOUS HISTORIES
37
- ...ctx.histories.map(ChatGptHistoryDecoder.decode).flat(),
38
- // USER INPUT
39
- {
40
- role: "user",
41
- content: ctx.prompt.text,
42
- },
43
- // SYSTEM PROMPT
44
- {
45
- role: "system",
46
- content:
47
- ctx.config?.systemPrompt?.execute?.(ctx.histories) ??
48
- AgenticaSystemPrompt.EXECUTE,
49
- },
50
- ],
51
- // STACKED FUNCTIONS
52
- tools: ctx.stack.map(
53
- (op) =>
54
- ({
55
- type: "function",
56
- function: {
57
- name: op.name,
58
- description: op.function.description,
59
- parameters: (op.function.separated
60
- ? (op.function.separated.llm ??
61
- ({
62
- type: "object",
63
- properties: {},
64
- required: [],
65
- additionalProperties: false,
66
- $defs: {},
67
- } satisfies IChatGptSchema.IParameters))
68
- : op.function.parameters) as Record<string, any>,
69
- },
70
- }) as OpenAI.ChatCompletionTool,
71
- ),
72
- tool_choice: "auto",
73
- parallel_tool_calls: false,
74
- });
75
-
76
- //----
77
- // PROCESS COMPLETION
78
- //----
79
- const closures: Array<
80
- () => Promise<
81
- Array<
82
- | IAgenticaPrompt.IExecute
83
- | IAgenticaPrompt.ICancel
84
- | IAgenticaPrompt.IText
85
- >
86
- >
87
- > = [];
88
- for (const choice of completion.choices) {
89
- for (const tc of choice.message.tool_calls ?? []) {
90
- if (tc.type === "function") {
91
- const operation: IAgenticaOperation | undefined =
92
- ctx.operations.flat.get(tc.function.name);
93
- if (operation === undefined) continue;
94
- closures.push(
95
- async (): Promise<
96
- [IAgenticaPrompt.IExecute, IAgenticaPrompt.ICancel]
97
- > => {
98
- const call: IAgenticaEvent.ICall = {
99
- type: "call",
100
- id: tc.id,
101
- operation,
102
- arguments: JSON.parse(tc.function.arguments),
103
- };
104
- if (call.operation.protocol === "http")
105
- fillHttpArguments({
106
- operation: call.operation,
107
- arguments: call.arguments,
108
- });
109
- await ctx.dispatch(call);
110
-
111
- const execute: IAgenticaPrompt.IExecute = await propagate(
112
- ctx,
113
- call,
114
- 0,
115
- );
116
- await ctx.dispatch({
117
- type: "execute",
118
- id: call.id,
119
- operation: call.operation,
120
- arguments: execute.arguments,
121
- value: execute.value,
122
- });
123
-
124
- await ChatGptCancelFunctionAgent.cancelFunction(ctx, {
125
- name: call.operation.name,
126
- reason: "completed",
127
- });
128
- await ctx.dispatch({
129
- type: "cancel",
130
- operation: call.operation,
131
- reason: "complete",
132
- });
133
- return [
134
- execute,
135
- {
136
- type: "cancel",
137
- id: call.id,
138
- operations: [
139
- AgenticaPromptFactory.selection({
140
- ...call.operation,
141
- reason: "complete",
142
- }),
143
- ],
144
- } satisfies IAgenticaPrompt.ICancel,
145
- ] as const;
146
- },
147
- );
148
- }
149
- }
150
- if (
151
- choice.message.role === "assistant" &&
152
- !!choice.message.content?.length
153
- )
154
- closures.push(async () => {
155
- const value: IAgenticaPrompt.IText = {
156
- type: "text",
157
- role: "assistant",
158
- text: choice.message.content!,
159
- };
160
- await ctx.dispatch(value);
161
- return [value];
162
- });
163
- }
164
- return (await Promise.all(closures.map((fn) => fn()))).flat();
165
- };
166
-
167
- const propagate = async (
168
- ctx: IAgenticaContext,
169
- call: IAgenticaEvent.ICall,
170
- retry: number,
171
- ): Promise<IAgenticaPrompt.IExecute> => {
172
- if (call.operation.protocol === "http") {
173
- //----
174
- // HTTP PROTOCOL
175
- //----
176
- try {
177
- // CALL HTTP API
178
- const response: IHttpResponse = call.operation.controller.execute
179
- ? await call.operation.controller.execute({
180
- connection: call.operation.controller.connection,
181
- application: call.operation.controller.application,
182
- function: call.operation.function,
183
- arguments: call.arguments,
184
- })
185
- : await HttpLlm.propagate({
186
- connection: call.operation.controller.connection,
187
- application: call.operation.controller.application,
188
- function: call.operation.function,
189
- input: call.arguments,
190
- });
191
- // CHECK STATUS
192
- const success: boolean =
193
- ((response.status === 400 ||
194
- response.status === 404 ||
195
- response.status === 422) &&
196
- retry++ < (ctx.config?.retry ?? AgenticaConstant.RETRY) &&
197
- typeof response.body) === false;
198
- // DISPATCH EVENT
199
- return (
200
- (success === false
201
- ? await correct(ctx, call, retry, response.body)
202
- : null) ??
203
- (await AgenticaPromptFactory.execute({
204
- type: "execute",
205
- protocol: "http",
206
- controller: call.operation.controller,
207
- function: call.operation.function,
208
- id: call.id,
209
- name: call.operation.name,
210
- arguments: call.arguments,
211
- value: response,
212
- }))
213
- );
214
- } catch (error) {
215
- // DISPATCH ERROR
216
- return AgenticaPromptFactory.execute({
217
- type: "execute",
218
- protocol: "http",
219
- controller: call.operation.controller,
220
- function: call.operation.function,
221
- id: call.id,
222
- name: call.operation.name,
223
- arguments: call.arguments,
224
- value: {
225
- status: 500,
226
- headers: {},
227
- body:
228
- error instanceof Error
229
- ? {
230
- ...error,
231
- name: error.name,
232
- message: error.message,
233
- }
234
- : error,
235
- },
236
- });
237
- }
238
- } else {
239
- //----
240
- // CLASS FUNCTION
241
- //----
242
- // VALIDATE FIRST
243
- const check: IValidation<unknown> = call.operation.function.validate(
244
- call.arguments,
245
- );
246
- if (check.success === false)
247
- return (
248
- (retry++ < (ctx.config?.retry ?? AgenticaConstant.RETRY)
249
- ? await correct(ctx, call, retry, check.errors)
250
- : null) ??
251
- AgenticaPromptFactory.execute({
252
- type: "execute",
253
- protocol: "class",
254
- controller: call.operation.controller,
255
- function: call.operation.function,
256
- id: call.id,
257
- name: call.operation.name,
258
- arguments: call.arguments,
259
- value: {
260
- name: "TypeGuardError",
261
- message: "Invalid arguments.",
262
- errors: check.errors,
263
- },
264
- })
265
- );
266
- // EXECUTE FUNCTION
267
- try {
268
- const value: any =
269
- typeof call.operation.controller.execute === "function"
270
- ? await call.operation.controller.execute({
271
- application: call.operation.controller.application,
272
- function: call.operation.function,
273
- arguments: call.arguments,
274
- })
275
- : await (call.operation.controller.execute as any)[
276
- call.operation.function.name
277
- ](call.arguments);
278
- return AgenticaPromptFactory.execute({
279
- type: "execute",
280
- protocol: "class",
281
- controller: call.operation.controller,
282
- function: call.operation.function,
283
- id: call.id,
284
- name: call.operation.name,
285
- arguments: call.arguments,
286
- value,
287
- });
288
- } catch (error) {
289
- return AgenticaPromptFactory.execute({
290
- type: "execute",
291
- protocol: "class",
292
- controller: call.operation.controller,
293
- function: call.operation.function,
294
- id: call.id,
295
- name: call.operation.name,
296
- arguments: call.arguments,
297
- value:
298
- error instanceof Error
299
- ? {
300
- ...error,
301
- name: error.name,
302
- message: error.message,
303
- }
304
- : error,
305
- });
306
- }
307
- }
308
- };
309
-
310
- const correct = async (
311
- ctx: IAgenticaContext,
312
- call: IAgenticaEvent.ICall,
313
- retry: number,
314
- error: unknown,
315
- ): Promise<IAgenticaPrompt.IExecute | null> => {
316
- //----
317
- // EXECUTE CHATGPT API
318
- //----
319
- const completion: OpenAI.ChatCompletion = await ctx.request("call", {
320
- messages: [
321
- // COMMON SYSTEM PROMPT
322
- {
323
- role: "system",
324
- content: AgenticaDefaultPrompt.write(ctx.config),
325
- } satisfies OpenAI.ChatCompletionSystemMessageParam,
326
- // PREVIOUS HISTORIES
327
- ...ctx.histories.map(ChatGptHistoryDecoder.decode).flat(),
328
- // USER INPUT
329
- {
330
- role: "user",
331
- content: ctx.prompt.text,
332
- },
333
- // TYPE CORRECTION
334
- {
335
- role: "system",
336
- content:
337
- ctx.config?.systemPrompt?.execute?.(ctx.histories) ??
338
- AgenticaSystemPrompt.EXECUTE,
339
- },
340
- {
341
- role: "assistant",
342
- tool_calls: [
343
- {
344
- type: "function",
345
- id: call.id,
346
- function: {
347
- name: call.operation.name,
348
- arguments: JSON.stringify(call.arguments),
349
- },
350
- } satisfies OpenAI.ChatCompletionMessageToolCall,
351
- ],
352
- } satisfies OpenAI.ChatCompletionAssistantMessageParam,
353
- {
354
- role: "tool",
355
- content: typeof error === "string" ? error : JSON.stringify(error),
356
- tool_call_id: call.id,
357
- } satisfies OpenAI.ChatCompletionToolMessageParam,
358
- {
359
- role: "system",
360
- content: [
361
- "You A.I. assistant has composed wrong arguments.",
362
- "",
363
- "Correct it at the next function calling.",
364
- ].join("\n"),
365
- },
366
- ],
367
- // STACK FUNCTIONS
368
- tools: [
369
- {
370
- type: "function",
371
- function: {
372
- name: call.operation.name,
373
- description: call.operation.function.description,
374
- parameters: (call.operation.function.separated
375
- ? (call.operation.function.separated?.llm ??
376
- ({
377
- $defs: {},
378
- type: "object",
379
- properties: {},
380
- additionalProperties: false,
381
- required: [],
382
- } satisfies IChatGptSchema.IParameters))
383
- : call.operation.function.parameters) as any,
384
- },
385
- },
386
- ],
387
- tool_choice: "auto",
388
- parallel_tool_calls: false,
389
- });
390
-
391
- //----
392
- // PROCESS COMPLETION
393
- //----
394
- const toolCall: OpenAI.ChatCompletionMessageToolCall | undefined = (
395
- completion.choices[0]?.message.tool_calls ?? []
396
- ).find(
397
- (tc) =>
398
- tc.type === "function" && tc.function.name === call.operation.name,
399
- );
400
- if (toolCall === undefined) return null;
401
- return propagate(
402
- ctx,
403
- {
404
- id: toolCall.id,
405
- type: "call",
406
- operation: call.operation,
407
- arguments: JSON.parse(toolCall.function.arguments),
408
- },
409
- retry,
410
- );
411
- };
412
-
413
- const fillHttpArguments = (props: {
414
- operation: IAgenticaOperation;
415
- arguments: object;
416
- }): void => {
417
- if (props.operation.protocol !== "http") return;
418
- const route: IHttpMigrateRoute = props.operation.function.route();
419
- if (
420
- route.body &&
421
- route.operation().requestBody?.required === true &&
422
- (props.arguments as any).body === undefined &&
423
- isObject(
424
- props.operation.function.parameters.$defs,
425
- props.operation.function.parameters.properties.body!,
426
- )
427
- )
428
- (props.arguments as any).body = {};
429
- if (route.query && (props.arguments as any).query === undefined)
430
- (props.arguments as any).query = {};
431
- };
432
-
433
- const isObject = (
434
- $defs: Record<string, IChatGptSchema>,
435
- schema: IChatGptSchema,
436
- ): boolean => {
437
- return (
438
- ChatGptTypeChecker.isObject(schema) ||
439
- (ChatGptTypeChecker.isReference(schema) &&
440
- isObject($defs, $defs[schema.$ref.split("/").at(-1)!]!)) ||
441
- (ChatGptTypeChecker.isAnyOf(schema) &&
442
- schema.anyOf.every((schema) => isObject($defs, schema)))
443
- );
444
- };
445
- }
1
+ import {
2
+ ChatGptTypeChecker,
3
+ HttpLlm,
4
+ IChatGptSchema,
5
+ IHttpMigrateRoute,
6
+ IHttpResponse,
7
+ ILlmSchema,
8
+ } from "@samchon/openapi";
9
+ import OpenAI from "openai";
10
+ import { IValidation } from "typia";
11
+
12
+ import { AgenticaConstant } from "../internal/AgenticaConstant";
13
+ import { AgenticaDefaultPrompt } from "../internal/AgenticaDefaultPrompt";
14
+ import { AgenticaPromptFactory } from "../internal/AgenticaPromptFactory";
15
+ import { AgenticaSystemPrompt } from "../internal/AgenticaSystemPrompt";
16
+ import { IAgenticaContext } from "../structures/IAgenticaContext";
17
+ import { IAgenticaEvent } from "../structures/IAgenticaEvent";
18
+ import { IAgenticaOperation } from "../structures/IAgenticaOperation";
19
+ import { IAgenticaPrompt } from "../structures/IAgenticaPrompt";
20
+ import { ChatGptCancelFunctionAgent } from "./ChatGptCancelFunctionAgent";
21
+ import { ChatGptHistoryDecoder } from "./ChatGptHistoryDecoder";
22
+
23
+ export namespace ChatGptCallFunctionAgent {
24
+ export const execute = async <Model extends ILlmSchema.Model>(
25
+ ctx: IAgenticaContext<Model>,
26
+ ): Promise<IAgenticaPrompt<Model>[]> => {
27
+ //----
28
+ // EXECUTE CHATGPT API
29
+ //----
30
+ const completion: OpenAI.ChatCompletion = await ctx.request("call", {
31
+ messages: [
32
+ // COMMON SYSTEM PROMPT
33
+ {
34
+ role: "system",
35
+ content: AgenticaDefaultPrompt.write(ctx.config),
36
+ } satisfies OpenAI.ChatCompletionSystemMessageParam,
37
+ // PREVIOUS HISTORIES
38
+ ...ctx.histories.map(ChatGptHistoryDecoder.decode).flat(),
39
+ // USER INPUT
40
+ {
41
+ role: "user",
42
+ content: ctx.prompt.text,
43
+ },
44
+ // SYSTEM PROMPT
45
+ {
46
+ role: "system",
47
+ content:
48
+ ctx.config?.systemPrompt?.execute?.(ctx.histories) ??
49
+ AgenticaSystemPrompt.EXECUTE,
50
+ },
51
+ ],
52
+ // STACKED FUNCTIONS
53
+ tools: ctx.stack.map(
54
+ (op) =>
55
+ ({
56
+ type: "function",
57
+ function: {
58
+ name: op.name,
59
+ description: op.function.description,
60
+ parameters: (op.function.separated
61
+ ? (op.function.separated.llm ??
62
+ ({
63
+ type: "object",
64
+ properties: {},
65
+ required: [],
66
+ additionalProperties: false,
67
+ $defs: {},
68
+ } satisfies IChatGptSchema.IParameters))
69
+ : op.function.parameters) as Record<string, any>,
70
+ },
71
+ }) as OpenAI.ChatCompletionTool,
72
+ ),
73
+ tool_choice: "auto",
74
+ parallel_tool_calls: false,
75
+ });
76
+
77
+ //----
78
+ // PROCESS COMPLETION
79
+ //----
80
+ const closures: Array<
81
+ () => Promise<
82
+ Array<
83
+ | IAgenticaPrompt.IExecute<Model>
84
+ | IAgenticaPrompt.ICancel<Model>
85
+ | IAgenticaPrompt.IText
86
+ >
87
+ >
88
+ > = [];
89
+ for (const choice of completion.choices) {
90
+ for (const tc of choice.message.tool_calls ?? []) {
91
+ if (tc.type === "function") {
92
+ const operation: IAgenticaOperation<Model> | undefined =
93
+ ctx.operations.flat.get(tc.function.name);
94
+ if (operation === undefined) continue;
95
+ closures.push(
96
+ async (): Promise<
97
+ [IAgenticaPrompt.IExecute<Model>, IAgenticaPrompt.ICancel<Model>]
98
+ > => {
99
+ const call: IAgenticaEvent.ICall<Model> = {
100
+ type: "call",
101
+ id: tc.id,
102
+ operation,
103
+ arguments: JSON.parse(tc.function.arguments),
104
+ };
105
+ if (call.operation.protocol === "http")
106
+ fillHttpArguments({
107
+ operation: call.operation,
108
+ arguments: call.arguments,
109
+ });
110
+ await ctx.dispatch(call);
111
+
112
+ const execute: IAgenticaPrompt.IExecute<Model> = await propagate(
113
+ ctx,
114
+ call,
115
+ 0,
116
+ );
117
+ await ctx.dispatch({
118
+ type: "execute",
119
+ id: call.id,
120
+ operation: call.operation,
121
+ arguments: execute.arguments,
122
+ value: execute.value,
123
+ });
124
+
125
+ await ChatGptCancelFunctionAgent.cancelFunction(ctx, {
126
+ name: call.operation.name,
127
+ reason: "completed",
128
+ });
129
+ await ctx.dispatch({
130
+ type: "cancel",
131
+ operation: call.operation,
132
+ reason: "complete",
133
+ });
134
+ return [
135
+ execute,
136
+ {
137
+ type: "cancel",
138
+ id: call.id,
139
+ operations: [
140
+ AgenticaPromptFactory.selection({
141
+ ...call.operation,
142
+ reason: "complete",
143
+ }),
144
+ ],
145
+ } satisfies IAgenticaPrompt.ICancel<Model>,
146
+ ] as const;
147
+ },
148
+ );
149
+ }
150
+ }
151
+ if (
152
+ choice.message.role === "assistant" &&
153
+ !!choice.message.content?.length
154
+ )
155
+ closures.push(async () => {
156
+ const value: IAgenticaPrompt.IText = {
157
+ type: "text",
158
+ role: "assistant",
159
+ text: choice.message.content!,
160
+ };
161
+ await ctx.dispatch(value);
162
+ return [value];
163
+ });
164
+ }
165
+ return (await Promise.all(closures.map((fn) => fn()))).flat();
166
+ };
167
+
168
+ const propagate = async <Model extends ILlmSchema.Model>(
169
+ ctx: IAgenticaContext<Model>,
170
+ call: IAgenticaEvent.ICall<Model>,
171
+ retry: number,
172
+ ): Promise<IAgenticaPrompt.IExecute<Model>> => {
173
+ if (call.operation.protocol === "http") {
174
+ //----
175
+ // HTTP PROTOCOL
176
+ //----
177
+ try {
178
+ // CALL HTTP API
179
+ const response: IHttpResponse = call.operation.controller.execute
180
+ ? await call.operation.controller.execute({
181
+ connection: call.operation.controller.connection,
182
+ application: call.operation.controller.application,
183
+ function: call.operation.function,
184
+ arguments: call.arguments,
185
+ })
186
+ : await HttpLlm.propagate({
187
+ connection: call.operation.controller.connection,
188
+ application: call.operation.controller.application,
189
+ function: call.operation.function,
190
+ input: call.arguments,
191
+ });
192
+ // CHECK STATUS
193
+ const success: boolean =
194
+ ((response.status === 400 ||
195
+ response.status === 404 ||
196
+ response.status === 422) &&
197
+ retry++ < (ctx.config?.retry ?? AgenticaConstant.RETRY) &&
198
+ typeof response.body) === false;
199
+ // DISPATCH EVENT
200
+ return (
201
+ (success === false
202
+ ? await correct(ctx, call, retry, response.body)
203
+ : null) ??
204
+ (await AgenticaPromptFactory.execute({
205
+ type: "execute",
206
+ protocol: "http",
207
+ controller: call.operation.controller,
208
+ function: call.operation.function,
209
+ id: call.id,
210
+ name: call.operation.name,
211
+ arguments: call.arguments,
212
+ value: response,
213
+ }))
214
+ );
215
+ } catch (error) {
216
+ // DISPATCH ERROR
217
+ return AgenticaPromptFactory.execute({
218
+ type: "execute",
219
+ protocol: "http",
220
+ controller: call.operation.controller,
221
+ function: call.operation.function,
222
+ id: call.id,
223
+ name: call.operation.name,
224
+ arguments: call.arguments,
225
+ value: {
226
+ status: 500,
227
+ headers: {},
228
+ body:
229
+ error instanceof Error
230
+ ? {
231
+ ...error,
232
+ name: error.name,
233
+ message: error.message,
234
+ }
235
+ : error,
236
+ },
237
+ });
238
+ }
239
+ } else {
240
+ //----
241
+ // CLASS FUNCTION
242
+ //----
243
+ // VALIDATE FIRST
244
+ const check: IValidation<unknown> = call.operation.function.validate(
245
+ call.arguments,
246
+ );
247
+ if (check.success === false)
248
+ return (
249
+ (retry++ < (ctx.config?.retry ?? AgenticaConstant.RETRY)
250
+ ? await correct(ctx, call, retry, check.errors)
251
+ : null) ??
252
+ AgenticaPromptFactory.execute({
253
+ type: "execute",
254
+ protocol: "class",
255
+ controller: call.operation.controller,
256
+ function: call.operation.function,
257
+ id: call.id,
258
+ name: call.operation.name,
259
+ arguments: call.arguments,
260
+ value: {
261
+ name: "TypeGuardError",
262
+ message: "Invalid arguments.",
263
+ errors: check.errors,
264
+ },
265
+ })
266
+ );
267
+ // EXECUTE FUNCTION
268
+ try {
269
+ const value: any =
270
+ typeof call.operation.controller.execute === "function"
271
+ ? await call.operation.controller.execute({
272
+ application: call.operation.controller.application,
273
+ function: call.operation.function,
274
+ arguments: call.arguments,
275
+ })
276
+ : await (call.operation.controller.execute as any)[
277
+ call.operation.function.name
278
+ ](call.arguments);
279
+ return AgenticaPromptFactory.execute({
280
+ type: "execute",
281
+ protocol: "class",
282
+ controller: call.operation.controller,
283
+ function: call.operation.function,
284
+ id: call.id,
285
+ name: call.operation.name,
286
+ arguments: call.arguments,
287
+ value,
288
+ });
289
+ } catch (error) {
290
+ return AgenticaPromptFactory.execute({
291
+ type: "execute",
292
+ protocol: "class",
293
+ controller: call.operation.controller,
294
+ function: call.operation.function,
295
+ id: call.id,
296
+ name: call.operation.name,
297
+ arguments: call.arguments,
298
+ value:
299
+ error instanceof Error
300
+ ? {
301
+ ...error,
302
+ name: error.name,
303
+ message: error.message,
304
+ }
305
+ : error,
306
+ });
307
+ }
308
+ }
309
+ };
310
+
311
+ const correct = async <Model extends ILlmSchema.Model>(
312
+ ctx: IAgenticaContext<Model>,
313
+ call: IAgenticaEvent.ICall<Model>,
314
+ retry: number,
315
+ error: unknown,
316
+ ): Promise<IAgenticaPrompt.IExecute<Model> | null> => {
317
+ //----
318
+ // EXECUTE CHATGPT API
319
+ //----
320
+ const completion: OpenAI.ChatCompletion = await ctx.request("call", {
321
+ messages: [
322
+ // COMMON SYSTEM PROMPT
323
+ {
324
+ role: "system",
325
+ content: AgenticaDefaultPrompt.write(ctx.config),
326
+ } satisfies OpenAI.ChatCompletionSystemMessageParam,
327
+ // PREVIOUS HISTORIES
328
+ ...ctx.histories.map(ChatGptHistoryDecoder.decode).flat(),
329
+ // USER INPUT
330
+ {
331
+ role: "user",
332
+ content: ctx.prompt.text,
333
+ },
334
+ // TYPE CORRECTION
335
+ {
336
+ role: "system",
337
+ content:
338
+ ctx.config?.systemPrompt?.execute?.(ctx.histories) ??
339
+ AgenticaSystemPrompt.EXECUTE,
340
+ },
341
+ {
342
+ role: "assistant",
343
+ tool_calls: [
344
+ {
345
+ type: "function",
346
+ id: call.id,
347
+ function: {
348
+ name: call.operation.name,
349
+ arguments: JSON.stringify(call.arguments),
350
+ },
351
+ } satisfies OpenAI.ChatCompletionMessageToolCall,
352
+ ],
353
+ } satisfies OpenAI.ChatCompletionAssistantMessageParam,
354
+ {
355
+ role: "tool",
356
+ content: typeof error === "string" ? error : JSON.stringify(error),
357
+ tool_call_id: call.id,
358
+ } satisfies OpenAI.ChatCompletionToolMessageParam,
359
+ {
360
+ role: "system",
361
+ content: [
362
+ "You A.I. assistant has composed wrong arguments.",
363
+ "",
364
+ "Correct it at the next function calling.",
365
+ ].join("\n"),
366
+ },
367
+ ],
368
+ // STACK FUNCTIONS
369
+ tools: [
370
+ {
371
+ type: "function",
372
+ function: {
373
+ name: call.operation.name,
374
+ description: call.operation.function.description,
375
+ parameters: (call.operation.function.separated
376
+ ? (call.operation.function.separated?.llm ??
377
+ ({
378
+ $defs: {},
379
+ type: "object",
380
+ properties: {},
381
+ additionalProperties: false,
382
+ required: [],
383
+ } satisfies IChatGptSchema.IParameters))
384
+ : call.operation.function.parameters) as any,
385
+ },
386
+ },
387
+ ],
388
+ tool_choice: "auto",
389
+ parallel_tool_calls: false,
390
+ });
391
+
392
+ //----
393
+ // PROCESS COMPLETION
394
+ //----
395
+ const toolCall: OpenAI.ChatCompletionMessageToolCall | undefined = (
396
+ completion.choices[0]?.message.tool_calls ?? []
397
+ ).find(
398
+ (tc) =>
399
+ tc.type === "function" && tc.function.name === call.operation.name,
400
+ );
401
+ if (toolCall === undefined) return null;
402
+ return propagate(
403
+ ctx,
404
+ {
405
+ id: toolCall.id,
406
+ type: "call",
407
+ operation: call.operation,
408
+ arguments: JSON.parse(toolCall.function.arguments),
409
+ },
410
+ retry,
411
+ );
412
+ };
413
+
414
+ const fillHttpArguments = <Model extends ILlmSchema.Model>(props: {
415
+ operation: IAgenticaOperation<Model>;
416
+ arguments: object;
417
+ }): void => {
418
+ if (props.operation.protocol !== "http") return;
419
+ const route: IHttpMigrateRoute = props.operation.function.route();
420
+ if (
421
+ route.body &&
422
+ route.operation().requestBody?.required === true &&
423
+ (props.arguments as any).body === undefined &&
424
+ isObject(
425
+ (props.operation.function.parameters as IChatGptSchema.IParameters)
426
+ .$defs,
427
+ (props.operation.function.parameters as IChatGptSchema.IParameters)
428
+ .properties.body!,
429
+ )
430
+ )
431
+ (props.arguments as any).body = {};
432
+ if (route.query && (props.arguments as any).query === undefined)
433
+ (props.arguments as any).query = {};
434
+ };
435
+
436
+ const isObject = (
437
+ $defs: Record<string, IChatGptSchema>,
438
+ schema: IChatGptSchema,
439
+ ): boolean => {
440
+ return (
441
+ ChatGptTypeChecker.isObject(schema) ||
442
+ (ChatGptTypeChecker.isReference(schema) &&
443
+ isObject($defs, $defs[schema.$ref.split("/").at(-1)!]!)) ||
444
+ (ChatGptTypeChecker.isAnyOf(schema) &&
445
+ schema.anyOf.every((schema) => isObject($defs, schema)))
446
+ );
447
+ };
448
+ }