@agentica/core 0.12.20 → 0.13.0

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 (205) hide show
  1. package/README.md +50 -47
  2. package/lib/Agentica.d.ts +9 -9
  3. package/lib/Agentica.js +23 -16
  4. package/lib/Agentica.js.map +1 -1
  5. package/lib/chatgpt/ChatGptAgent.d.ts +7 -7
  6. package/lib/chatgpt/ChatGptAgent.js +17 -12
  7. package/lib/chatgpt/ChatGptAgent.js.map +1 -1
  8. package/lib/chatgpt/ChatGptCallFunctionAgent.d.ts +7 -6
  9. package/lib/chatgpt/ChatGptCallFunctionAgent.js +121 -81
  10. package/lib/chatgpt/ChatGptCallFunctionAgent.js.map +1 -1
  11. package/lib/chatgpt/ChatGptCancelFunctionAgent.d.ts +9 -7
  12. package/lib/chatgpt/ChatGptCancelFunctionAgent.js +177 -145
  13. package/lib/chatgpt/ChatGptCancelFunctionAgent.js.map +1 -1
  14. package/lib/chatgpt/ChatGptCompletionMessageUtil.d.ts +13 -8
  15. package/lib/chatgpt/ChatGptCompletionMessageUtil.js +499 -489
  16. package/lib/chatgpt/ChatGptCompletionMessageUtil.js.map +1 -1
  17. package/lib/chatgpt/ChatGptDescribeFunctionAgent.d.ts +7 -6
  18. package/lib/chatgpt/ChatGptDescribeFunctionAgent.js +33 -32
  19. package/lib/chatgpt/ChatGptDescribeFunctionAgent.js.map +1 -1
  20. package/lib/chatgpt/ChatGptHistoryDecoder.d.ts +7 -6
  21. package/lib/chatgpt/ChatGptHistoryDecoder.js +60 -56
  22. package/lib/chatgpt/ChatGptHistoryDecoder.js.map +1 -1
  23. package/lib/chatgpt/ChatGptInitializeFunctionAgent.d.ts +7 -6
  24. package/lib/chatgpt/ChatGptInitializeFunctionAgent.js +121 -116
  25. package/lib/chatgpt/ChatGptInitializeFunctionAgent.js.map +1 -1
  26. package/lib/chatgpt/ChatGptSelectFunctionAgent.d.ts +20 -5
  27. package/lib/chatgpt/ChatGptSelectFunctionAgent.js +183 -150
  28. package/lib/chatgpt/ChatGptSelectFunctionAgent.js.map +1 -1
  29. package/lib/chatgpt/ChatGptUsageAggregator.d.ts +9 -6
  30. package/lib/chatgpt/ChatGptUsageAggregator.js +46 -41
  31. package/lib/chatgpt/ChatGptUsageAggregator.js.map +1 -1
  32. package/lib/context/AgenticaCancelPrompt.d.ts +3 -3
  33. package/lib/context/AgenticaCancelPrompt.js +1 -1
  34. package/lib/context/AgenticaCancelPrompt.js.map +1 -1
  35. package/lib/context/AgenticaClassOperation.d.ts +1 -1
  36. package/lib/context/AgenticaClassOperation.js.map +1 -1
  37. package/lib/context/AgenticaContext.d.ts +9 -9
  38. package/lib/context/AgenticaHttpOperation.d.ts +1 -1
  39. package/lib/context/AgenticaHttpOperation.js.map +1 -1
  40. package/lib/context/AgenticaOperation.d.ts +4 -4
  41. package/lib/context/AgenticaOperationBase.d.ts +1 -1
  42. package/lib/context/AgenticaOperationCollection.d.ts +2 -2
  43. package/lib/context/AgenticaOperationSelection.d.ts +3 -3
  44. package/lib/context/AgenticaTokenUsage.d.ts +1 -1
  45. package/lib/context/AgenticaTokenUsage.js.map +1 -1
  46. package/lib/context/internal/AgenticaTokenUsageAggregator.d.ts +11 -10
  47. package/lib/context/internal/AgenticaTokenUsageAggregator.js +42 -43
  48. package/lib/context/internal/AgenticaTokenUsageAggregator.js.map +1 -1
  49. package/lib/context/internal/__IChatCancelFunctionsApplication.d.ts +2 -2
  50. package/lib/context/internal/__IChatInitialApplication.d.ts +2 -2
  51. package/lib/context/internal/__IChatSelectFunctionsApplication.d.ts +2 -2
  52. package/lib/events/AgenticaCallEvent.d.ts +3 -3
  53. package/lib/events/AgenticaCancelEvent.d.ts +3 -3
  54. package/lib/events/AgenticaDescribeEvent.d.ts +3 -3
  55. package/lib/events/AgenticaDescribeEvent.js +13 -2
  56. package/lib/events/AgenticaDescribeEvent.js.map +1 -1
  57. package/lib/events/AgenticaEvent.d.ts +12 -12
  58. package/lib/events/AgenticaExecuteEvent.d.ts +7 -7
  59. package/lib/events/AgenticaInitializeEvent.d.ts +1 -1
  60. package/lib/events/AgenticaRequestEvent.d.ts +3 -3
  61. package/lib/events/AgenticaRequestEvent.js.map +1 -1
  62. package/lib/events/AgenticaResponseEvent.d.ts +2 -2
  63. package/lib/events/AgenticaResponseEvent.js.map +1 -1
  64. package/lib/events/AgenticaSelectEvent.d.ts +3 -3
  65. package/lib/events/AgenticaSelectEvent.js.map +1 -1
  66. package/lib/events/AgenticaTextEvent.d.ts +1 -1
  67. package/lib/events/AgenticaTextEvent.js +12 -1
  68. package/lib/events/AgenticaTextEvent.js.map +1 -1
  69. package/lib/functional/assertHttpLlmApplication.d.ts +4 -3
  70. package/lib/functional/assertHttpLlmApplication.js +9339 -9338
  71. package/lib/functional/assertHttpLlmApplication.js.map +1 -1
  72. package/lib/functional/validateHttpLlmApplication.d.ts +5 -4
  73. package/lib/functional/validateHttpLlmApplication.js +19 -19
  74. package/lib/functional/validateHttpLlmApplication.js.map +1 -1
  75. package/lib/index.d.ts +19 -19
  76. package/lib/index.js +21 -21
  77. package/lib/index.js.map +1 -1
  78. package/lib/index.mjs +19211 -18997
  79. package/lib/index.mjs.map +1 -1
  80. package/lib/internal/AgenticaDefaultPrompt.d.ts +6 -5
  81. package/lib/internal/AgenticaDefaultPrompt.js +39 -19
  82. package/lib/internal/AgenticaDefaultPrompt.js.map +1 -1
  83. package/lib/internal/AgenticaOperationComposer.d.ts +11 -10
  84. package/lib/internal/AgenticaOperationComposer.js +60 -59
  85. package/lib/internal/AgenticaOperationComposer.js.map +1 -1
  86. package/lib/internal/AgenticaSystemPrompt.d.ts +8 -8
  87. package/lib/internal/AgenticaSystemPrompt.js +9 -9
  88. package/lib/internal/AgenticaSystemPrompt.js.map +1 -1
  89. package/lib/internal/AsyncQueue.d.ts +15 -0
  90. package/lib/internal/AsyncQueue.js +82 -0
  91. package/lib/internal/AsyncQueue.js.map +1 -0
  92. package/lib/internal/ByteArrayUtil.d.ts +1 -1
  93. package/lib/internal/ByteArrayUtil.js +3 -2
  94. package/lib/internal/ByteArrayUtil.js.map +1 -1
  95. package/lib/internal/MPSC.d.ts +10 -0
  96. package/lib/internal/MPSC.js +49 -0
  97. package/lib/internal/MPSC.js.map +1 -0
  98. package/lib/internal/Singleton.js +6 -5
  99. package/lib/internal/Singleton.js.map +1 -1
  100. package/lib/internal/StreamUtil.d.ts +16 -6
  101. package/lib/internal/StreamUtil.js +43 -29
  102. package/lib/internal/StreamUtil.js.map +1 -1
  103. package/lib/internal/__map_take.js +5 -5
  104. package/lib/internal/__map_take.js.map +1 -1
  105. package/lib/json/IAgenticaEventJson.d.ts +7 -7
  106. package/lib/json/IAgenticaOperationSelectionJson.d.ts +1 -1
  107. package/lib/json/IAgenticaPromptJson.d.ts +2 -2
  108. package/lib/prompts/AgenticaCancelPrompt.d.ts +3 -3
  109. package/lib/prompts/AgenticaCancelPrompt.js +1 -1
  110. package/lib/prompts/AgenticaCancelPrompt.js.map +1 -1
  111. package/lib/prompts/AgenticaDescribePrompt.d.ts +3 -3
  112. package/lib/prompts/AgenticaDescribePrompt.js +1 -1
  113. package/lib/prompts/AgenticaDescribePrompt.js.map +1 -1
  114. package/lib/prompts/AgenticaExecutePrompt.d.ts +5 -5
  115. package/lib/prompts/AgenticaExecutePrompt.js.map +1 -1
  116. package/lib/prompts/AgenticaPrompt.d.ts +6 -6
  117. package/lib/prompts/AgenticaSelectPrompt.d.ts +3 -3
  118. package/lib/prompts/AgenticaSelectPrompt.js +1 -1
  119. package/lib/prompts/AgenticaSelectPrompt.js.map +1 -1
  120. package/lib/prompts/AgenticaTextPrompt.d.ts +1 -1
  121. package/lib/structures/IAgenticaConfig.d.ts +5 -5
  122. package/lib/structures/IAgenticaController.d.ts +1 -1
  123. package/lib/structures/IAgenticaExecutor.d.ts +4 -4
  124. package/lib/structures/IAgenticaProps.d.ts +5 -5
  125. package/lib/structures/IAgenticaSystemPrompt.d.ts +4 -4
  126. package/lib/structures/IAgenticaVendor.d.ts +1 -1
  127. package/lib/transformers/AgenticaEventTransformer.d.ts +55 -37
  128. package/lib/transformers/AgenticaEventTransformer.js +105 -58
  129. package/lib/transformers/AgenticaEventTransformer.js.map +1 -1
  130. package/lib/transformers/AgenticaPromptTransformer.d.ts +35 -29
  131. package/lib/transformers/AgenticaPromptTransformer.js +74 -45
  132. package/lib/transformers/AgenticaPromptTransformer.js.map +1 -1
  133. package/package.json +20 -23
  134. package/prompts/cancel.md +1 -1
  135. package/prompts/common.md +1 -1
  136. package/prompts/describe.md +1 -1
  137. package/prompts/execute.md +1 -1
  138. package/prompts/initialize.md +1 -1
  139. package/prompts/select.md +1 -1
  140. package/src/Agentica.ts +41 -31
  141. package/src/chatgpt/ChatGptAgent.ts +63 -57
  142. package/src/chatgpt/ChatGptCallFunctionAgent.ts +363 -337
  143. package/src/chatgpt/ChatGptCancelFunctionAgent.ts +188 -164
  144. package/src/chatgpt/ChatGptCompletionMessageUtil.ts +136 -137
  145. package/src/chatgpt/ChatGptDescribeFunctionAgent.ts +105 -101
  146. package/src/chatgpt/ChatGptHistoryDecoder.ts +69 -65
  147. package/src/chatgpt/ChatGptInitializeFunctionAgent.ts +128 -123
  148. package/src/chatgpt/ChatGptSelectFunctionAgent.ts +215 -189
  149. package/src/chatgpt/ChatGptUsageAggregator.ts +49 -54
  150. package/src/context/AgenticaCancelPrompt.ts +4 -4
  151. package/src/context/AgenticaClassOperation.ts +5 -5
  152. package/src/context/AgenticaContext.ts +15 -15
  153. package/src/context/AgenticaHttpOperation.ts +5 -5
  154. package/src/context/AgenticaOperation.ts +4 -4
  155. package/src/context/AgenticaOperationBase.ts +1 -1
  156. package/src/context/AgenticaOperationCollection.ts +2 -2
  157. package/src/context/AgenticaOperationSelection.ts +3 -3
  158. package/src/context/AgenticaTokenUsage.ts +4 -3
  159. package/src/context/internal/AgenticaTokenUsageAggregator.ts +59 -59
  160. package/src/context/internal/__IChatCancelFunctionsApplication.ts +2 -2
  161. package/src/context/internal/__IChatInitialApplication.ts +2 -2
  162. package/src/context/internal/__IChatSelectFunctionsApplication.ts +2 -2
  163. package/src/events/AgenticaCallEvent.ts +3 -3
  164. package/src/events/AgenticaCancelEvent.ts +3 -3
  165. package/src/events/AgenticaDescribeEvent.ts +5 -5
  166. package/src/events/AgenticaEvent.ts +12 -12
  167. package/src/events/AgenticaExecuteEvent.ts +7 -7
  168. package/src/events/AgenticaInitializeEvent.ts +1 -1
  169. package/src/events/AgenticaRequestEvent.ts +3 -3
  170. package/src/events/AgenticaResponseEvent.ts +2 -2
  171. package/src/events/AgenticaSelectEvent.ts +4 -4
  172. package/src/events/AgenticaTextEvent.ts +2 -2
  173. package/src/functional/assertHttpLlmApplication.ts +9 -6
  174. package/src/functional/validateHttpLlmApplication.ts +14 -8
  175. package/src/index.ts +24 -24
  176. package/src/internal/AgenticaDefaultPrompt.ts +42 -28
  177. package/src/internal/AgenticaOperationComposer.ts +63 -61
  178. package/src/internal/AgenticaSystemPrompt.ts +15 -14
  179. package/src/internal/AsyncQueue.ts +67 -0
  180. package/src/internal/ByteArrayUtil.ts +2 -2
  181. package/src/internal/MPSC.ts +40 -0
  182. package/src/internal/Singleton.ts +8 -6
  183. package/src/internal/StreamUtil.ts +62 -53
  184. package/src/internal/__map_take.ts +5 -7
  185. package/src/json/IAgenticaEventJson.ts +7 -8
  186. package/src/json/IAgenticaOperationSelectionJson.ts +1 -1
  187. package/src/json/IAgenticaPromptJson.ts +2 -2
  188. package/src/prompts/AgenticaCancelPrompt.ts +4 -4
  189. package/src/prompts/AgenticaDescribePrompt.ts +4 -4
  190. package/src/prompts/AgenticaExecutePrompt.ts +6 -5
  191. package/src/prompts/AgenticaPrompt.ts +6 -6
  192. package/src/prompts/AgenticaSelectPrompt.ts +4 -4
  193. package/src/prompts/AgenticaTextPrompt.ts +1 -1
  194. package/src/structures/IAgenticaConfig.ts +5 -5
  195. package/src/structures/IAgenticaController.ts +14 -14
  196. package/src/structures/IAgenticaExecutor.ts +4 -4
  197. package/src/structures/IAgenticaProps.ts +5 -5
  198. package/src/structures/IAgenticaSystemPrompt.ts +4 -4
  199. package/src/structures/IAgenticaVendor.ts +1 -1
  200. package/src/transformers/AgenticaEventTransformer.ts +169 -136
  201. package/src/transformers/AgenticaPromptTransformer.ts +125 -103
  202. package/lib/internal/MPSCUtil.d.ts +0 -35
  203. package/lib/internal/MPSCUtil.js +0 -105
  204. package/lib/internal/MPSCUtil.js.map +0 -1
  205. package/src/internal/MPSCUtil.ts +0 -111
@@ -1,17 +1,20 @@
1
- import {
2
- ChatGptTypeChecker,
3
- HttpLlm,
1
+ import type {
4
2
  IChatGptSchema,
5
3
  IHttpMigrateRoute,
6
4
  IHttpResponse,
7
5
  ILlmSchema,
8
6
  } from "@samchon/openapi";
9
- import OpenAI from "openai";
10
- import { IValidation } from "typia";
7
+ import type OpenAI from "openai";
8
+ import type { IValidation } from "typia";
9
+ import type { AgenticaContext } from "../context/AgenticaContext";
11
10
 
11
+ import type { AgenticaOperation } from "../context/AgenticaOperation";
12
+ import type { AgenticaPrompt } from "../prompts/AgenticaPrompt";
13
+ import {
14
+ ChatGptTypeChecker,
15
+ HttpLlm,
16
+ } from "@samchon/openapi";
12
17
  import { AgenticaCancelPrompt } from "../context/AgenticaCancelPrompt";
13
- import { AgenticaContext } from "../context/AgenticaContext";
14
- import { AgenticaOperation } from "../context/AgenticaOperation";
15
18
  import { AgenticaOperationSelection } from "../context/AgenticaOperationSelection";
16
19
  import { AgenticaCallEvent } from "../events/AgenticaCallEvent";
17
20
  import { AgenticaCancelEvent } from "../events/AgenticaCancelEvent";
@@ -22,21 +25,17 @@ import { AgenticaDefaultPrompt } from "../internal/AgenticaDefaultPrompt";
22
25
  import { AgenticaSystemPrompt } from "../internal/AgenticaSystemPrompt";
23
26
  import { StreamUtil } from "../internal/StreamUtil";
24
27
  import { AgenticaExecutePrompt } from "../prompts/AgenticaExecutePrompt";
25
- import { AgenticaPrompt } from "../prompts/AgenticaPrompt";
26
28
  import { AgenticaTextPrompt } from "../prompts/AgenticaTextPrompt";
27
29
  import { ChatGptCancelFunctionAgent } from "./ChatGptCancelFunctionAgent";
28
30
  import { ChatGptCompletionMessageUtil } from "./ChatGptCompletionMessageUtil";
29
31
  import { ChatGptHistoryDecoder } from "./ChatGptHistoryDecoder";
30
32
 
31
- export namespace ChatGptCallFunctionAgent {
32
- export const execute = async <Model extends ILlmSchema.Model>(
33
- ctx: AgenticaContext<Model>,
34
- ): Promise<AgenticaPrompt<Model>[]> => {
35
- //----
36
- // EXECUTE CHATGPT API
37
- //----
38
- const completionStream = await ctx.request("call", {
39
- messages: [
33
+ export async function execute<Model extends ILlmSchema.Model>(ctx: AgenticaContext<Model>): Promise<AgenticaPrompt<Model>[]> {
34
+ // ----
35
+ // EXECUTE CHATGPT API
36
+ // ----
37
+ const completionStream = await ctx.request("call", {
38
+ messages: [
40
39
  // COMMON SYSTEM PROMPT
41
40
  {
42
41
  role: "system",
@@ -53,208 +52,201 @@ export namespace ChatGptCallFunctionAgent {
53
52
  {
54
53
  role: "system",
55
54
  content:
56
- ctx.config?.systemPrompt?.execute?.(ctx.histories) ??
57
- AgenticaSystemPrompt.EXECUTE,
55
+ ctx.config?.systemPrompt?.execute?.(ctx.histories)
56
+ ?? AgenticaSystemPrompt.EXECUTE,
58
57
  },
59
- ],
60
- // STACKED FUNCTIONS
61
- tools: ctx.stack.map(
62
- (s) =>
63
- ({
64
- type: "function",
65
- function: {
66
- name: s.operation.name,
67
- description: s.operation.function.description,
68
- parameters: (s.operation.function.separated
69
- ? (s.operation.function.separated.llm ??
70
- ({
71
- type: "object",
72
- properties: {},
73
- required: [],
74
- additionalProperties: false,
75
- $defs: {},
76
- } satisfies IChatGptSchema.IParameters))
77
- : s.operation.function.parameters) as Record<string, any>,
78
- },
79
- }) as OpenAI.ChatCompletionTool,
80
- ),
81
- tool_choice: "auto",
82
- parallel_tool_calls: false,
83
- });
58
+ ],
59
+ // STACKED FUNCTIONS
60
+ tools: ctx.stack.map(
61
+ s =>
62
+ ({
63
+ type: "function",
64
+ function: {
65
+ name: s.operation.name,
66
+ description: s.operation.function.description,
67
+ parameters: (s.operation.function.separated !== undefined
68
+ ? (s.operation.function.separated.llm
69
+ ?? ({
70
+ type: "object",
71
+ properties: {},
72
+ required: [],
73
+ additionalProperties: false,
74
+ $defs: {},
75
+ } satisfies IChatGptSchema.IParameters))
76
+ : s.operation.function.parameters) as Record<string, any>,
77
+ },
78
+ }) as OpenAI.ChatCompletionTool,
79
+ ),
80
+ tool_choice: "auto",
81
+ parallel_tool_calls: false,
82
+ });
84
83
 
85
- //----
86
- // PROCESS COMPLETION
87
- //----
88
- const closures: Array<
89
- () => Promise<
90
- Array<
91
- | AgenticaExecutePrompt<Model>
92
- | AgenticaCancelPrompt<Model>
93
- | AgenticaTextPrompt
94
- >
84
+ // ----
85
+ // PROCESS COMPLETION
86
+ // ----
87
+ const closures: Array<
88
+ () => Promise<
89
+ Array<
90
+ | AgenticaExecutePrompt<Model>
91
+ | AgenticaCancelPrompt<Model>
92
+ | AgenticaTextPrompt
95
93
  >
96
- > = [];
94
+ >
95
+ > = [];
97
96
 
98
- const chunks = await StreamUtil.readAll(completionStream);
99
- const completion = ChatGptCompletionMessageUtil.merge(chunks);
97
+ const chunks = await StreamUtil.readAll(completionStream);
98
+ const completion = ChatGptCompletionMessageUtil.merge(chunks);
100
99
 
101
- for (const choice of completion.choices) {
102
- for (const tc of choice.message.tool_calls ?? []) {
103
- if (tc.type === "function") {
104
- const operation: AgenticaOperation<Model> | undefined =
105
- ctx.operations.flat.get(tc.function.name);
106
- if (operation === undefined) continue;
107
- closures.push(
108
- async (): Promise<
109
- [AgenticaExecutePrompt<Model>, AgenticaCancelPrompt<Model>]
110
- > => {
111
- const call: AgenticaCallEvent<Model> = new AgenticaCallEvent({
112
- id: tc.id,
113
- operation,
114
- arguments: JSON.parse(tc.function.arguments),
100
+ for (const choice of completion.choices) {
101
+ for (const tc of choice.message.tool_calls ?? []) {
102
+ if (tc.type === "function") {
103
+ const operation: AgenticaOperation<Model> | undefined
104
+ = ctx.operations.flat.get(tc.function.name);
105
+ if (operation === undefined) {
106
+ continue;
107
+ }
108
+ closures.push(
109
+ async (): Promise<
110
+ [AgenticaExecutePrompt<Model>, AgenticaCancelPrompt<Model>]
111
+ > => {
112
+ const call: AgenticaCallEvent<Model> = new AgenticaCallEvent({
113
+ id: tc.id,
114
+ operation,
115
+ // @TODO add type assertion!
116
+ arguments: JSON.parse(tc.function.arguments) as Record<string, unknown>,
117
+ });
118
+ if (call.operation.protocol === "http") {
119
+ fillHttpArguments({
120
+ operation: call.operation,
121
+ arguments: call.arguments,
115
122
  });
116
- if (call.operation.protocol === "http")
117
- fillHttpArguments({
118
- operation: call.operation,
119
- arguments: call.arguments,
120
- });
121
- await ctx.dispatch(call);
123
+ }
124
+ await ctx.dispatch(call);
125
+
126
+ const execute: AgenticaExecutePrompt<Model> = await propagate(
127
+ ctx,
128
+ call,
129
+ 0,
130
+ );
131
+ await ctx.dispatch(
132
+ new AgenticaExecuteEvent({
133
+ id: call.id,
134
+ operation: call.operation,
135
+ arguments: execute.arguments,
136
+ value: execute.value,
137
+ }),
138
+ );
122
139
 
123
- const execute: AgenticaExecutePrompt<Model> = await propagate(
124
- ctx,
125
- call,
126
- 0,
127
- );
128
- await ctx.dispatch(
129
- new AgenticaExecuteEvent({
130
- id: call.id,
140
+ await ChatGptCancelFunctionAgent.cancelFunction(ctx, {
141
+ name: call.operation.name,
142
+ reason: "completed",
143
+ });
144
+ await ctx.dispatch(
145
+ new AgenticaCancelEvent({
146
+ selection: new AgenticaOperationSelection({
131
147
  operation: call.operation,
132
- arguments: execute.arguments,
133
- value: execute.value,
148
+ reason: "complete",
134
149
  }),
135
- );
136
-
137
- await ChatGptCancelFunctionAgent.cancelFunction(ctx, {
138
- name: call.operation.name,
139
- reason: "completed",
140
- });
141
- await ctx.dispatch(
142
- new AgenticaCancelEvent({
143
- selection: new AgenticaOperationSelection({
150
+ }),
151
+ );
152
+ return [
153
+ execute,
154
+ new AgenticaCancelPrompt({
155
+ id: call.id,
156
+ selections: [
157
+ new AgenticaOperationSelection({
144
158
  operation: call.operation,
145
159
  reason: "complete",
146
160
  }),
147
- }),
148
- );
149
- return [
150
- execute,
151
- new AgenticaCancelPrompt({
152
- id: call.id,
153
- selections: [
154
- new AgenticaOperationSelection({
155
- operation: call.operation,
156
- reason: "complete",
157
- }),
158
- ],
159
- }),
160
- ] as const;
161
- },
162
- );
163
- }
161
+ ],
162
+ }),
163
+ ] as const;
164
+ },
165
+ );
164
166
  }
165
- if (
166
- choice.message.role === "assistant" &&
167
- !!choice.message.content?.length
168
- )
169
- closures.push(async () => {
170
- const value: AgenticaTextPrompt = new AgenticaTextPrompt({
171
- role: "assistant",
172
- text: choice.message.content!,
173
- });
174
- await ctx.dispatch(
175
- new AgenticaTextEvent({
176
- role: "assistant",
177
- get: () => value.text,
178
- done: () => true,
179
- stream: StreamUtil.to(value.text),
180
- join: () => Promise.resolve(value.text),
181
- }),
182
- );
183
- return [value];
167
+ }
168
+ if (
169
+ choice.message.role === "assistant"
170
+ && choice.message.content !== null
171
+ && choice.message.content.length > 0
172
+ ) {
173
+ closures.push(async () => {
174
+ const value: AgenticaTextPrompt = new AgenticaTextPrompt({
175
+ role: "assistant",
176
+ text: choice.message.content!,
184
177
  });
178
+ await ctx.dispatch(
179
+ new AgenticaTextEvent({
180
+ role: "assistant",
181
+ get: () => value.text,
182
+ done: () => true,
183
+ stream: StreamUtil.to(value.text),
184
+ join: async () => Promise.resolve(value.text),
185
+ }),
186
+ );
187
+ return [value];
188
+ });
185
189
  }
186
- return (await Promise.all(closures.map((fn) => fn()))).flat();
187
- };
190
+ }
191
+ return (await Promise.all(closures.map(async fn => fn()))).flat();
192
+ }
188
193
 
189
- const propagate = async <Model extends ILlmSchema.Model>(
190
- ctx: AgenticaContext<Model>,
191
- call: AgenticaCallEvent<Model>,
192
- retry: number,
193
- ): Promise<AgenticaExecutePrompt<Model>> => {
194
- if (call.operation.protocol === "http") {
195
- //----
196
- // HTTP PROTOCOL
197
- //----
198
- // NESTED VALIDATOR
199
- const check: IValidation<unknown> = call.operation.function.validate(
200
- call.arguments,
194
+ async function propagate<Model extends ILlmSchema.Model>(ctx: AgenticaContext<Model>, call: AgenticaCallEvent<Model>, retry: number): Promise<AgenticaExecutePrompt<Model>> {
195
+ if (call.operation.protocol === "http") {
196
+ // ----
197
+ // HTTP PROTOCOL
198
+ // ----
199
+ // NESTED VALIDATOR
200
+ const check: IValidation<unknown> = call.operation.function.validate(
201
+ call.arguments,
202
+ );
203
+ if (
204
+ check.success === false
205
+ && retry++ < (ctx.config?.retry ?? AgenticaConstant.RETRY)
206
+ ) {
207
+ const trial: AgenticaExecutePrompt<Model> | null = await correct(
208
+ ctx,
209
+ call,
210
+ retry,
211
+ check.errors,
201
212
  );
202
- if (
203
- check.success === false &&
204
- retry++ < (ctx.config?.retry ?? AgenticaConstant.RETRY)
205
- ) {
206
- const trial: AgenticaExecutePrompt<Model> | null = await correct(
207
- ctx,
208
- call,
209
- retry,
210
- check.errors,
211
- );
212
- if (trial !== null) return trial;
213
+ if (trial !== null) {
214
+ return trial;
213
215
  }
214
- try {
215
- // CALL HTTP API
216
- const response: IHttpResponse = call.operation.controller.execute
217
- ? await call.operation.controller.execute({
218
- connection: call.operation.controller.connection,
219
- application: call.operation.controller.application,
220
- function: call.operation.function,
221
- arguments: call.arguments,
222
- })
223
- : await HttpLlm.propagate({
224
- connection: call.operation.controller.connection,
225
- application: call.operation.controller.application,
226
- function: call.operation.function,
227
- input: call.arguments,
228
- });
229
- // CHECK STATUS
230
- const success: boolean =
231
- ((response.status === 400 ||
232
- response.status === 404 ||
233
- response.status === 422) &&
234
- retry++ < (ctx.config?.retry ?? AgenticaConstant.RETRY) &&
235
- typeof response.body) === false;
216
+ }
217
+ try {
218
+ // CALL HTTP API
219
+ const response: IHttpResponse = await executeHttpOperation(call.operation, call.arguments);
220
+ // CHECK STATUS
221
+ const success: boolean
222
+ = ((response.status === 400
223
+ || response.status === 404
224
+ || response.status === 422)
225
+ && retry++ < (ctx.config?.retry ?? AgenticaConstant.RETRY)
226
+ && typeof response.body) === false;
236
227
  // DISPATCH EVENT
237
- return (
238
- (success === false
239
- ? await correct(ctx, call, retry, response.body)
240
- : null) ??
241
- new AgenticaExecutePrompt({
242
- operation: call.operation,
243
- id: call.id,
244
- arguments: call.arguments,
245
- value: response,
246
- })
247
- );
248
- } catch (error) {
249
- // DISPATCH ERROR
250
- return new AgenticaExecutePrompt({
228
+ return (
229
+ (success === false
230
+ ? await correct(ctx, call, retry, response.body)
231
+ : null)
232
+ ?? new AgenticaExecutePrompt({
251
233
  operation: call.operation,
252
234
  id: call.id,
253
235
  arguments: call.arguments,
254
- value: {
255
- status: 500,
256
- headers: {},
257
- body:
236
+ value: response,
237
+ })
238
+ );
239
+ }
240
+ catch (error) {
241
+ // DISPATCH ERROR
242
+ return new AgenticaExecutePrompt({
243
+ operation: call.operation,
244
+ id: call.id,
245
+ arguments: call.arguments,
246
+ value: {
247
+ status: 500,
248
+ headers: {},
249
+ body:
258
250
  error instanceof Error
259
251
  ? {
260
252
  ...error,
@@ -262,57 +254,51 @@ export namespace ChatGptCallFunctionAgent {
262
254
  message: error.message,
263
255
  }
264
256
  : error,
265
- },
266
- });
267
- }
268
- } else {
269
- //----
270
- // CLASS FUNCTION
271
- //----
272
- // VALIDATE FIRST
273
- const check: IValidation<unknown> = call.operation.function.validate(
274
- call.arguments,
275
- );
276
- if (check.success === false)
277
- return (
278
- (retry++ < (ctx.config?.retry ?? AgenticaConstant.RETRY)
279
- ? await correct(ctx, call, retry, check.errors)
280
- : null) ??
281
- new AgenticaExecutePrompt({
282
- id: call.id,
283
- operation: call.operation,
284
- arguments: call.arguments,
285
- value: {
286
- name: "TypeGuardError",
287
- message: "Invalid arguments.",
288
- errors: check.errors,
289
- },
290
- })
291
- );
292
- // EXECUTE FUNCTION
293
- try {
294
- const value: any =
295
- typeof call.operation.controller.execute === "function"
296
- ? await call.operation.controller.execute({
297
- application: call.operation.controller.application,
298
- function: call.operation.function,
299
- arguments: call.arguments,
300
- })
301
- : await (call.operation.controller.execute as any)[
302
- call.operation.function.name
303
- ](call.arguments);
304
- return new AgenticaExecutePrompt({
305
- id: call.id,
306
- operation: call.operation,
307
- arguments: call.arguments,
308
- value,
309
- });
310
- } catch (error) {
311
- return new AgenticaExecutePrompt({
257
+ },
258
+ });
259
+ }
260
+ }
261
+ else {
262
+ // ----
263
+ // CLASS FUNCTION
264
+ // ----
265
+ // VALIDATE FIRST
266
+ const check: IValidation<unknown> = call.operation.function.validate(
267
+ call.arguments,
268
+ );
269
+ if (check.success === false) {
270
+ return (
271
+ (retry++ < (ctx.config?.retry ?? AgenticaConstant.RETRY)
272
+ ? await correct(ctx, call, retry, check.errors)
273
+ : null)
274
+ ?? new AgenticaExecutePrompt({
312
275
  id: call.id,
313
276
  operation: call.operation,
314
277
  arguments: call.arguments,
315
- value:
278
+ value: {
279
+ name: "TypeGuardError",
280
+ message: "Invalid arguments.",
281
+ errors: check.errors,
282
+ },
283
+ })
284
+ );
285
+ }
286
+ // EXECUTE FUNCTION
287
+ try {
288
+ const value = await executeClassOperation(call.operation, call.arguments);
289
+ return new AgenticaExecutePrompt({
290
+ id: call.id,
291
+ operation: call.operation,
292
+ arguments: call.arguments,
293
+ value,
294
+ });
295
+ }
296
+ catch (error) {
297
+ return new AgenticaExecutePrompt({
298
+ id: call.id,
299
+ operation: call.operation,
300
+ arguments: call.arguments,
301
+ value:
316
302
  error instanceof Error
317
303
  ? {
318
304
  ...error,
@@ -320,22 +306,53 @@ export namespace ChatGptCallFunctionAgent {
320
306
  message: error.message,
321
307
  }
322
308
  : error,
323
- });
324
- }
309
+ });
325
310
  }
311
+ }
312
+ }
313
+
314
+ async function executeHttpOperation<Model extends ILlmSchema.Model>(operation: AgenticaOperation.Http<Model>, operationArguments: Record<string, unknown>): Promise<IHttpResponse> {
315
+ const controllerBaseArguments = {
316
+ connection: operation.controller.connection,
317
+ application: operation.controller.application,
318
+ function: operation.function,
326
319
  };
327
320
 
328
- const correct = async <Model extends ILlmSchema.Model>(
329
- ctx: AgenticaContext<Model>,
330
- call: AgenticaCallEvent<Model>,
331
- retry: number,
332
- error: unknown,
333
- ): Promise<AgenticaExecutePrompt<Model> | null> => {
334
- //----
335
- // EXECUTE CHATGPT API
336
- //----
337
- const completionStream = await ctx.request("call", {
338
- messages: [
321
+ return operation.controller.execute !== undefined
322
+ ? operation.controller.execute({ ...controllerBaseArguments, arguments: operationArguments })
323
+ : HttpLlm.propagate({ ...controllerBaseArguments, input: operationArguments });
324
+ }
325
+
326
+ /**
327
+ * @throws {TypeError}
328
+ */
329
+ async function executeClassOperation<Model extends ILlmSchema.Model>(operation: AgenticaOperation.Class<Model>, operationArguments: Record<string, unknown>): Promise<unknown> {
330
+ const execute = operation.controller.execute;
331
+ if (typeof execute === "function") {
332
+ return await execute({
333
+ application: operation.controller.application,
334
+ function: operation.function,
335
+ arguments: operationArguments,
336
+ });
337
+ }
338
+
339
+ // As you know, it's very unstable logic.
340
+ // But this is an intended error.
341
+ // There are two types of errors that can occur here.
342
+ // One is a TypeError caused by referencing an undefined value, and the other is a TypeError caused by calling something that isn't a function.
343
+ // These errors are intentional, and any call to this function must be wrapped in a try-catch block.
344
+ // Unless there is an overall structural improvement, this function will remain as-is.
345
+
346
+ const executeFunction = (execute as Record<string, unknown>)[operation.function.name];
347
+ return (executeFunction as (...args: unknown[]) => Promise<unknown>)(operationArguments);
348
+ }
349
+
350
+ async function correct<Model extends ILlmSchema.Model>(ctx: AgenticaContext<Model>, call: AgenticaCallEvent<Model>, retry: number, error: unknown): Promise<AgenticaExecutePrompt<Model> | null> {
351
+ // ----
352
+ // EXECUTE CHATGPT API
353
+ // ----
354
+ const completionStream = await ctx.request("call", {
355
+ messages: [
339
356
  // COMMON SYSTEM PROMPT
340
357
  {
341
358
  role: "system",
@@ -352,8 +369,8 @@ export namespace ChatGptCallFunctionAgent {
352
369
  {
353
370
  role: "system",
354
371
  content:
355
- ctx.config?.systemPrompt?.execute?.(ctx.histories) ??
356
- AgenticaSystemPrompt.EXECUTE,
372
+ ctx.config?.systemPrompt?.execute?.(ctx.histories)
373
+ ?? AgenticaSystemPrompt.EXECUTE,
357
374
  },
358
375
  {
359
376
  role: "assistant",
@@ -381,86 +398,95 @@ export namespace ChatGptCallFunctionAgent {
381
398
  "Correct it at the next function calling.",
382
399
  ].join("\n"),
383
400
  },
384
- ],
385
- // STACK FUNCTIONS
386
- tools: [
387
- {
388
- type: "function",
389
- function: {
390
- name: call.operation.name,
391
- description: call.operation.function.description,
392
- parameters: (call.operation.function.separated
393
- ? (call.operation.function.separated?.llm ??
394
- ({
395
- $defs: {},
396
- type: "object",
397
- properties: {},
398
- additionalProperties: false,
399
- required: [],
400
- } satisfies IChatGptSchema.IParameters))
401
- : call.operation.function.parameters) as any,
402
- },
401
+ ],
402
+ // STACK FUNCTIONS
403
+ tools: [
404
+ {
405
+ type: "function",
406
+ function: {
407
+ name: call.operation.name,
408
+ description: call.operation.function.description,
409
+ /**
410
+ * @TODO fix it
411
+ * The property and value have a type mismatch, but it works.
412
+ */
413
+ parameters: (call.operation.function.separated !== undefined
414
+ ? (call.operation.function.separated?.llm
415
+ ?? ({
416
+ $defs: {},
417
+ type: "object",
418
+ properties: {},
419
+ additionalProperties: false,
420
+ required: [],
421
+ } satisfies IChatGptSchema.IParameters))
422
+ : call.operation.function.parameters) as unknown as Record<string, unknown>,
403
423
  },
404
- ],
405
- tool_choice: "auto",
406
- parallel_tool_calls: false,
407
- });
424
+ },
425
+ ],
426
+ tool_choice: "auto",
427
+ parallel_tool_calls: false,
428
+ });
408
429
 
409
- const chunks = await StreamUtil.readAll(completionStream);
410
- const completion = ChatGptCompletionMessageUtil.merge(chunks);
411
- //----
412
- // PROCESS COMPLETION
413
- //----
414
- const toolCall: OpenAI.ChatCompletionMessageToolCall | undefined = (
415
- completion.choices[0]?.message.tool_calls ?? []
416
- ).find(
417
- (tc) =>
418
- tc.type === "function" && tc.function.name === call.operation.name,
419
- );
420
- if (toolCall === undefined) return null;
421
- return propagate(
422
- ctx,
423
- new AgenticaCallEvent({
424
- id: toolCall.id,
425
- operation: call.operation,
426
- arguments: JSON.parse(toolCall.function.arguments),
427
- }),
428
- retry,
429
- );
430
- };
430
+ const chunks = await StreamUtil.readAll(completionStream);
431
+ const completion = ChatGptCompletionMessageUtil.merge(chunks);
432
+ // ----
433
+ // PROCESS COMPLETION
434
+ // ----
435
+ const toolCall: OpenAI.ChatCompletionMessageToolCall | undefined = (
436
+ completion.choices[0]?.message.tool_calls ?? []
437
+ ).find(
438
+ tc =>
439
+ tc.type === "function" && tc.function.name === call.operation.name,
440
+ );
441
+ if (toolCall === undefined) {
442
+ return null;
443
+ }
444
+ return propagate(
445
+ ctx,
446
+ new AgenticaCallEvent({
447
+ id: toolCall.id,
448
+ operation: call.operation,
449
+ arguments: JSON.parse(toolCall.function.arguments) as Record<string, unknown>,
450
+ }),
451
+ retry,
452
+ );
453
+ }
431
454
 
432
- const fillHttpArguments = <Model extends ILlmSchema.Model>(props: {
433
- operation: AgenticaOperation<Model>;
434
- arguments: object;
435
- }): void => {
436
- if (props.operation.protocol !== "http") return;
437
- const route: IHttpMigrateRoute = props.operation.function.route();
438
- if (
439
- route.body &&
440
- route.operation().requestBody?.required === true &&
441
- (props.arguments as any).body === undefined &&
442
- isObject(
443
- (props.operation.function.parameters as IChatGptSchema.IParameters)
444
- .$defs,
445
- (props.operation.function.parameters as IChatGptSchema.IParameters)
446
- .properties.body!,
447
- )
455
+ function fillHttpArguments<Model extends ILlmSchema.Model>(props: {
456
+ operation: AgenticaOperation<Model>;
457
+ arguments: Record<string, unknown>;
458
+ }): void {
459
+ if (props.operation.protocol !== "http") {
460
+ return;
461
+ }
462
+ const route: IHttpMigrateRoute = props.operation.function.route();
463
+ if (
464
+ route.body !== null
465
+ && route.operation().requestBody?.required === true
466
+ && "body" in props.arguments
467
+ && isObject(
468
+ (props.operation.function.parameters as IChatGptSchema.IParameters)
469
+ .$defs,
470
+ (props.operation.function.parameters as IChatGptSchema.IParameters)
471
+ .properties
472
+ .body!,
448
473
  )
449
- (props.arguments as any).body = {};
450
- if (route.query && (props.arguments as any).query === undefined)
451
- (props.arguments as any).query = {};
452
- };
474
+ ) { props.arguments.body = {}; }
475
+ if (route.query !== null && "query" in props.arguments && props.arguments.query === undefined) {
476
+ props.arguments.query = {};
477
+ }
478
+ }
453
479
 
454
- const isObject = (
455
- $defs: Record<string, IChatGptSchema>,
456
- schema: IChatGptSchema,
457
- ): boolean => {
458
- return (
459
- ChatGptTypeChecker.isObject(schema) ||
460
- (ChatGptTypeChecker.isReference(schema) &&
461
- isObject($defs, $defs[schema.$ref.split("/").at(-1)!]!)) ||
462
- (ChatGptTypeChecker.isAnyOf(schema) &&
463
- schema.anyOf.every((schema) => isObject($defs, schema)))
464
- );
465
- };
480
+ function isObject($defs: Record<string, IChatGptSchema>, schema: IChatGptSchema): boolean {
481
+ return (
482
+ ChatGptTypeChecker.isObject(schema)
483
+ || (ChatGptTypeChecker.isReference(schema)
484
+ && isObject($defs, $defs[schema.$ref.split("/").at(-1)!]!))
485
+ || (ChatGptTypeChecker.isAnyOf(schema)
486
+ && schema.anyOf.every(schema => isObject($defs, schema)))
487
+ );
466
488
  }
489
+
490
+ export const ChatGptCallFunctionAgent = {
491
+ execute,
492
+ };