@agentica/core 0.12.21 → 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,4 +1,4 @@
1
- import {
1
+ import type {
2
2
  ChatCompletion,
3
3
  ChatCompletionChunk,
4
4
  ChatCompletionMessage,
@@ -10,160 +10,159 @@ import { json } from "typia";
10
10
  import { ByteArrayUtil } from "../internal/ByteArrayUtil";
11
11
  import { ChatGptUsageAggregator } from "./ChatGptUsageAggregator";
12
12
 
13
- export namespace ChatGptCompletionMessageUtil {
14
- export const transformCompletionChunk = (
15
- source: string | Uint8Array,
16
- ): ChatCompletionChunk => {
17
- const str =
18
- source instanceof Uint8Array ? ByteArrayUtil.toUtf8(source) : source;
19
- return json.assertParse<
13
+ export function transformCompletionChunk(source: string | Uint8Array): ChatCompletionChunk {
14
+ const str
15
+ = source instanceof Uint8Array ? ByteArrayUtil.toUtf8(source) : source;
16
+ return json.assertParse<
20
17
  ChatCompletionChunk & { usage: CompletionUsage | null | undefined }
21
- >(str);
22
- };
18
+ >(str);
19
+ }
23
20
 
24
- export const accumulate = (
25
- origin: ChatCompletion,
26
- chunk: ChatCompletionChunk,
27
- ): ChatCompletion => {
28
- const choices = origin.choices;
29
- chunk.choices.forEach((choice) => {
30
- const accChoice = choices[choice.index];
31
- if (accChoice) {
32
- choices[choice.index] = mergeChoice(accChoice, choice);
33
- return;
34
- }
21
+ export function accumulate(origin: ChatCompletion, chunk: ChatCompletionChunk): ChatCompletion {
22
+ const choices = origin.choices;
23
+ chunk.choices.forEach((choice) => {
24
+ const accChoice = choices[choice.index];
25
+ if (accChoice != null) {
26
+ choices[choice.index] = mergeChoice(accChoice, choice);
27
+ return;
28
+ }
35
29
 
36
- choices[choice.index] = {
37
- index: choice.index,
38
-
39
- finish_reason:
40
- choice.finish_reason ??
41
- (null as unknown as ChatCompletion.Choice["finish_reason"]),
42
-
43
- logprobs: choice.logprobs ?? null,
44
- message: {
45
- tool_calls: choice.delta.tool_calls
46
- ? choice.delta.tool_calls.reduce((acc, cur) => {
47
- acc[cur.index] = {
48
- id: cur.id ?? "",
49
- type: "function",
50
- function: {
51
- name: cur.function?.name ?? "",
52
- arguments: cur.function?.arguments ?? "",
53
- },
54
- };
55
- return acc;
56
- }, [] as ChatCompletionMessageToolCall[])
57
- : undefined,
58
- content: choice.delta.content ?? null,
59
- refusal: choice.delta.refusal ?? null,
60
- role: "assistant",
61
- } satisfies ChatCompletionMessage,
62
- };
63
- });
30
+ choices[choice.index] = {
31
+ index: choice.index,
32
+
33
+ finish_reason:
34
+ choice.finish_reason
35
+ ?? (null as unknown as ChatCompletion.Choice["finish_reason"]),
36
+
37
+ logprobs: choice.logprobs ?? null,
38
+ message: {
39
+ tool_calls: choice.delta.tool_calls !== undefined
40
+ ? choice.delta.tool_calls.reduce((acc, cur) => {
41
+ acc[cur.index] = {
42
+ id: cur.id ?? "",
43
+ type: "function",
44
+ function: {
45
+ name: cur.function?.name ?? "",
46
+ arguments: cur.function?.arguments ?? "",
47
+ },
48
+ };
49
+ return acc;
50
+ }, [] as ChatCompletionMessageToolCall[])
51
+ : undefined,
52
+ content: choice.delta.content ?? null,
53
+ refusal: choice.delta.refusal ?? null,
54
+ role: "assistant",
55
+ } satisfies ChatCompletionMessage,
56
+ };
57
+ });
64
58
 
65
- const usage = (() => {
66
- if (!chunk.usage) {
67
- return origin.usage;
68
- }
59
+ const usage = (() => {
60
+ if (chunk.usage == null) {
61
+ return origin.usage;
62
+ }
69
63
 
70
- if (!origin.usage) {
71
- return chunk.usage;
72
- }
64
+ if (origin.usage == null) {
65
+ return chunk.usage;
66
+ }
73
67
 
74
- return ChatGptUsageAggregator.sum(origin.usage, chunk.usage);
75
- })();
68
+ return ChatGptUsageAggregator.sum(origin.usage, chunk.usage);
69
+ })();
76
70
 
77
- return {
78
- ...origin,
79
- choices,
80
- usage,
81
- };
71
+ return {
72
+ ...origin,
73
+ choices,
74
+ usage,
82
75
  };
76
+ }
83
77
 
84
- export const merge = (chunks: ChatCompletionChunk[]): ChatCompletion => {
85
- const firstChunk = chunks[0];
86
- if (!firstChunk) throw new Error("No chunks received");
87
-
88
- return chunks.reduce(ChatGptCompletionMessageUtil.accumulate, {
89
- id: firstChunk.id,
90
- choices: [],
91
- created: firstChunk.created,
92
- model: firstChunk.model,
93
- object: "chat.completion",
94
- usage: undefined,
95
- service_tier: firstChunk.service_tier,
96
- system_fingerprint: firstChunk.system_fingerprint,
97
- } as ChatCompletion);
98
- };
78
+ export function merge(chunks: ChatCompletionChunk[]): ChatCompletion {
79
+ const firstChunk = chunks[0];
80
+ if (firstChunk === undefined) {
81
+ throw new Error("No chunks received");
82
+ }
83
+
84
+ return chunks.reduce(accumulate, {
85
+ id: firstChunk.id,
86
+ choices: [],
87
+ created: firstChunk.created,
88
+ model: firstChunk.model,
89
+ object: "chat.completion",
90
+ usage: undefined,
91
+ service_tier: firstChunk.service_tier,
92
+ system_fingerprint: firstChunk.system_fingerprint,
93
+ } as ChatCompletion);
94
+ }
99
95
 
100
- export const mergeChoice = (
101
- acc: ChatCompletion.Choice,
102
- cur: ChatCompletionChunk.Choice,
103
- ): ChatCompletion.Choice => {
104
- if (!acc.finish_reason && cur.finish_reason) {
105
- acc.finish_reason = cur.finish_reason;
106
- }
96
+ export function mergeChoice(acc: ChatCompletion.Choice, cur: ChatCompletionChunk.Choice): ChatCompletion.Choice {
97
+ if (acc.finish_reason == null && cur.finish_reason != null) {
98
+ acc.finish_reason = cur.finish_reason;
99
+ }
107
100
 
108
- if (!acc.logprobs && cur.logprobs) {
109
- acc.logprobs = cur.logprobs;
110
- }
101
+ if (acc.logprobs == null && cur.logprobs != null) {
102
+ acc.logprobs = cur.logprobs;
103
+ }
111
104
 
112
- if (cur.delta.content) {
113
- if (!acc.message.content) {
114
- acc.message.content = cur.delta.content;
115
- } else {
116
- acc.message.content += cur.delta.content;
117
- }
105
+ if (cur.delta.content != null) {
106
+ if (acc.message.content == null) {
107
+ acc.message.content = cur.delta.content;
118
108
  }
119
-
120
- if (cur.delta.refusal) {
121
- if (!acc.message.refusal) {
122
- acc.message.refusal = cur.delta.refusal;
123
- } else {
124
- acc.message.refusal += cur.delta.refusal;
125
- }
109
+ else {
110
+ acc.message.content += cur.delta.content;
126
111
  }
112
+ }
127
113
 
128
- if (cur.delta.tool_calls) {
129
- acc.message.tool_calls ??= [];
130
- const toolCalls = acc.message.tool_calls;
131
-
132
- cur.delta.tool_calls.forEach((toolCall) => {
133
- const existingToolCall = toolCalls[toolCall.index];
134
- if (existingToolCall) {
135
- toolCalls[toolCall.index] = mergeToolCalls(
136
- existingToolCall,
137
- toolCall,
138
- );
139
- return;
140
- }
141
-
142
- toolCalls[toolCall.index] = {
143
- id: toolCall.id ?? "",
144
- type: "function",
145
- function: {
146
- name: toolCall.function?.name ?? "",
147
- arguments: toolCall.function?.arguments ?? "",
148
- },
149
- };
150
- });
114
+ if (cur.delta.refusal != null) {
115
+ if (acc.message.refusal == null) {
116
+ acc.message.refusal = cur.delta.refusal;
117
+ }
118
+ else {
119
+ acc.message.refusal += cur.delta.refusal;
151
120
  }
121
+ }
122
+
123
+ if (cur.delta.tool_calls != null) {
124
+ acc.message.tool_calls ??= [];
125
+ const toolCalls = acc.message.tool_calls;
126
+
127
+ cur.delta.tool_calls.forEach((toolCall) => {
128
+ const existingToolCall = toolCalls[toolCall.index];
129
+ if (existingToolCall != null) {
130
+ toolCalls[toolCall.index] = mergeToolCalls(
131
+ existingToolCall,
132
+ toolCall,
133
+ );
134
+ return;
135
+ }
152
136
 
153
- return acc;
154
- };
137
+ toolCalls[toolCall.index] = {
138
+ id: toolCall.id ?? "",
139
+ type: "function",
140
+ function: {
141
+ name: toolCall.function?.name ?? "",
142
+ arguments: toolCall.function?.arguments ?? "",
143
+ },
144
+ };
145
+ });
146
+ }
155
147
 
156
- export const mergeToolCalls = (
157
- acc: ChatCompletionMessageToolCall,
158
- cur: ChatCompletionChunk.Choice.Delta.ToolCall,
159
- ): ChatCompletionMessageToolCall => {
160
- if (cur.function) {
161
- acc.function.arguments += cur.function.arguments ?? "";
162
- acc.function.name += cur.function.name ?? "";
163
- }
148
+ return acc;
149
+ }
164
150
 
165
- acc.id += cur.id ?? "";
151
+ export function mergeToolCalls(acc: ChatCompletionMessageToolCall, cur: ChatCompletionChunk.Choice.Delta.ToolCall): ChatCompletionMessageToolCall {
152
+ if (cur.function != null) {
153
+ acc.function.arguments += cur.function.arguments ?? "";
154
+ acc.function.name += cur.function.name ?? "";
155
+ }
166
156
 
167
- return acc;
168
- };
157
+ acc.id += cur.id ?? "";
158
+
159
+ return acc;
169
160
  }
161
+
162
+ export const ChatGptCompletionMessageUtil = {
163
+ transformCompletionChunk,
164
+ accumulate,
165
+ merge,
166
+ mergeChoice,
167
+ mergeToolCalls,
168
+ };
@@ -1,122 +1,126 @@
1
- import { ILlmSchema } from "@samchon/openapi";
2
- import OpenAI from "openai";
1
+ import type { ILlmSchema } from "@samchon/openapi";
2
+ import type OpenAI from "openai";
3
3
 
4
- import { AgenticaContext } from "../context/AgenticaContext";
4
+ import type { AgenticaContext } from "../context/AgenticaContext";
5
+ import type { AgenticaExecutePrompt } from "../prompts/AgenticaExecutePrompt";
5
6
  import { AgenticaDescribeEvent } from "../events/AgenticaDescribeEvent";
6
7
  import { AgenticaDefaultPrompt } from "../internal/AgenticaDefaultPrompt";
7
8
  import { AgenticaSystemPrompt } from "../internal/AgenticaSystemPrompt";
8
- import { MPSCUtil } from "../internal/MPSCUtil";
9
+ import { MPSC } from "../internal/MPSC";
9
10
  import { StreamUtil } from "../internal/StreamUtil";
10
11
  import { AgenticaDescribePrompt } from "../prompts/AgenticaDescribePrompt";
11
- import { AgenticaExecutePrompt } from "../prompts/AgenticaExecutePrompt";
12
12
  import { ChatGptCompletionMessageUtil } from "./ChatGptCompletionMessageUtil";
13
13
  import { ChatGptHistoryDecoder } from "./ChatGptHistoryDecoder";
14
14
 
15
- export namespace ChatGptDescribeFunctionAgent {
16
- export const execute = async <Model extends ILlmSchema.Model>(
17
- ctx: AgenticaContext<Model>,
18
- histories: AgenticaExecutePrompt<Model>[],
19
- ): Promise<AgenticaDescribePrompt<Model>[]> => {
20
- if (histories.length === 0) return [];
21
- const completionStream = await ctx.request("describe", {
22
- messages: [
23
- // COMMON SYSTEM PROMPT
24
- {
25
- role: "system",
26
- content: AgenticaDefaultPrompt.write(ctx.config),
27
- } satisfies OpenAI.ChatCompletionSystemMessageParam,
28
- // FUNCTION CALLING HISTORIES
29
- ...histories.map(ChatGptHistoryDecoder.decode).flat(),
30
- // SYSTEM PROMPT
31
- {
32
- role: "system",
33
- content:
34
- ctx.config?.systemPrompt?.describe?.(histories) ??
35
- AgenticaSystemPrompt.DESCRIBE,
36
- },
37
- ],
38
- });
15
+ export async function execute<Model extends ILlmSchema.Model>(ctx: AgenticaContext<Model>, histories: AgenticaExecutePrompt<Model>[]): Promise<AgenticaDescribePrompt<Model>[]> {
16
+ if (histories.length === 0) {
17
+ return [];
18
+ }
39
19
 
40
- const describeContext: ({
41
- content: string;
42
- } & ReturnType<typeof MPSCUtil.create<string>>)[] = [];
20
+ const completionStream = await ctx.request("describe", {
21
+ messages: [
22
+ // COMMON SYSTEM PROMPT
23
+ {
24
+ role: "system",
25
+ content: AgenticaDefaultPrompt.write(ctx.config),
26
+ } satisfies OpenAI.ChatCompletionSystemMessageParam,
27
+ // FUNCTION CALLING HISTORIES
28
+ ...histories.map(ChatGptHistoryDecoder.decode).flat(),
29
+ // SYSTEM PROMPT
30
+ {
31
+ role: "system",
32
+ content:
33
+ ctx.config?.systemPrompt?.describe?.(histories)
34
+ ?? AgenticaSystemPrompt.DESCRIBE,
35
+ },
36
+ ],
37
+ });
43
38
 
44
- const completion = await StreamUtil.reduce<
45
- OpenAI.ChatCompletionChunk,
46
- Promise<OpenAI.ChatCompletion>
47
- >(completionStream, async (accPromise, chunk) => {
48
- const acc = await accPromise;
49
- const registerContext = (
50
- choices: OpenAI.ChatCompletionChunk.Choice[],
51
- ) => {
52
- for (const choice of choices) {
53
- if (choice.finish_reason) {
54
- describeContext[choice.index]!.close();
55
- continue;
56
- }
57
- if (!choice.delta.content) {
58
- continue;
59
- }
39
+ const describeContext: ({
40
+ content: string;
41
+ mpsc: MPSC<string>;
42
+ })[] = [];
60
43
 
61
- if (describeContext[choice.index]) {
62
- describeContext[choice.index]!.content += choice.delta.content;
63
- describeContext[choice.index]!.produce(choice.delta.content);
64
- continue;
65
- }
66
-
67
- const { consumer, produce, close, waitClosed, waitUntilEmpty, done } =
68
- MPSCUtil.create<string>();
44
+ const completion = await StreamUtil.reduce<
45
+ OpenAI.ChatCompletionChunk,
46
+ Promise<OpenAI.ChatCompletion>
47
+ >(completionStream, async (accPromise, chunk) => {
48
+ const acc = await accPromise;
49
+ const registerContext = (
50
+ choices: OpenAI.ChatCompletionChunk.Choice[],
51
+ ) => {
52
+ for (const choice of choices) {
53
+ /**
54
+ * @TODO fix it
55
+ * Sometimes, the complete message arrives along with a finish reason.
56
+ */
57
+ if (choice.finish_reason != null) {
58
+ describeContext[choice.index]!.mpsc.close();
59
+ continue;
60
+ }
69
61
 
70
- describeContext[choice.index] = {
71
- content: choice.delta.content,
72
- consumer,
73
- produce,
74
- close,
75
- waitClosed,
76
- waitUntilEmpty,
77
- done,
78
- };
79
- produce(choice.delta.content);
62
+ if (choice.delta.content == null) {
63
+ continue;
64
+ }
80
65
 
81
- void ctx.dispatch(
82
- new AgenticaDescribeEvent({
83
- executes: histories,
84
- stream: consumer,
85
- done,
86
- get: () => describeContext[choice.index]?.content ?? "",
87
- join: async () => {
88
- await waitClosed();
89
- return describeContext[choice.index]!.content;
90
- },
91
- }),
92
- );
66
+ if (describeContext[choice.index] != null) {
67
+ describeContext[choice.index]!.content += choice.delta.content;
68
+ describeContext[choice.index]!.mpsc.produce(choice.delta.content);
69
+ continue;
93
70
  }
94
- };
95
71
 
96
- if (acc.object === "chat.completion.chunk") {
97
- registerContext([acc, chunk].flatMap((v) => v.choices));
98
- return ChatGptCompletionMessageUtil.merge([acc, chunk]);
99
- }
72
+ const mpsc = new MPSC<string>();
100
73
 
101
- registerContext(chunk.choices);
102
- return ChatGptCompletionMessageUtil.accumulate(acc, chunk);
103
- });
74
+ describeContext[choice.index] = {
75
+ content: choice.delta.content,
76
+ mpsc,
77
+ };
78
+ mpsc.produce(choice.delta.content);
104
79
 
105
- if (!completion) throw new Error("No completion received");
106
- const descriptions: AgenticaDescribePrompt<Model>[] = completion.choices
107
- .map((choice) =>
108
- choice.message.role === "assistant" && !!choice.message.content?.length
109
- ? choice.message.content
110
- : null,
111
- )
112
- .filter((str) => str !== null)
113
- .map(
114
- (content) =>
115
- new AgenticaDescribePrompt({
80
+ void ctx.dispatch(
81
+ new AgenticaDescribeEvent({
116
82
  executes: histories,
117
- text: content,
83
+ stream: mpsc.consumer,
84
+ done: () => mpsc.done(),
85
+ get: () => describeContext[choice.index]?.content ?? "",
86
+ join: async () => {
87
+ await mpsc.waitClosed();
88
+ return describeContext[choice.index]!.content;
89
+ },
118
90
  }),
119
- );
120
- return descriptions;
121
- };
91
+ );
92
+ }
93
+ };
94
+
95
+ if (acc.object === "chat.completion.chunk") {
96
+ registerContext([acc, chunk].flatMap(v => v.choices));
97
+ return ChatGptCompletionMessageUtil.merge([acc, chunk]);
98
+ }
99
+
100
+ registerContext(chunk.choices);
101
+ return ChatGptCompletionMessageUtil.accumulate(acc, chunk);
102
+ });
103
+
104
+ if (completion == null) {
105
+ throw new Error("No completion received");
106
+ }
107
+ const descriptions: AgenticaDescribePrompt<Model>[] = completion.choices
108
+ .map(choice =>
109
+ choice.message.role === "assistant"
110
+ ? choice.message.content
111
+ : null,
112
+ )
113
+ .filter(str => str !== null)
114
+ .map(
115
+ content =>
116
+ new AgenticaDescribePrompt({
117
+ executes: histories,
118
+ text: content,
119
+ }),
120
+ );
121
+ return descriptions;
122
122
  }
123
+
124
+ export const ChatGptDescribeFunctionAgent = {
125
+ execute,
126
+ };
@@ -1,48 +1,22 @@
1
- import { ILlmSchema } from "@samchon/openapi";
2
- import OpenAI from "openai";
1
+ import type { IHttpResponse, ILlmSchema } from "@samchon/openapi";
2
+ import type OpenAI from "openai";
3
3
 
4
- import { AgenticaPrompt } from "../prompts/AgenticaPrompt";
5
-
6
- export namespace ChatGptHistoryDecoder {
7
- export const decode = <Model extends ILlmSchema.Model>(
8
- history: AgenticaPrompt<Model>,
9
- ): OpenAI.ChatCompletionMessageParam[] => {
10
- // NO NEED TO DECODE DESCRIBE
11
- if (history.type === "describe") return [];
12
- else if (history.type === "text")
13
- return [
14
- {
15
- role: history.role,
16
- content: history.text,
17
- },
18
- ];
19
- else if (history.type === "select" || history.type === "cancel")
20
- return [
21
- {
22
- role: "assistant",
23
- tool_calls: [
24
- {
25
- type: "function",
26
- id: history.id,
27
- function: {
28
- name: `${history.type}Functions`,
29
- arguments: JSON.stringify({
30
- functions: history.selections.map((s) => ({
31
- name: s.operation.function.name,
32
- reason: s.reason,
33
- })),
34
- }),
35
- },
36
- },
37
- ],
38
- },
39
- {
40
- role: "tool",
41
- tool_call_id: history.id,
42
- content: "",
43
- },
44
- ];
4
+ import type { AgenticaPrompt } from "../prompts/AgenticaPrompt";
45
5
 
6
+ export function decode<Model extends ILlmSchema.Model>(history: AgenticaPrompt<Model>): OpenAI.ChatCompletionMessageParam[] {
7
+ // NO NEED TO DECODE DESCRIBE
8
+ if (history.type === "describe") {
9
+ return [];
10
+ }
11
+ else if (history.type === "text") {
12
+ return [
13
+ {
14
+ role: history.role,
15
+ content: history.text,
16
+ },
17
+ ];
18
+ }
19
+ else if (history.type === "select" || history.type === "cancel") {
46
20
  return [
47
21
  {
48
22
  role: "assistant",
@@ -51,8 +25,13 @@ export namespace ChatGptHistoryDecoder {
51
25
  type: "function",
52
26
  id: history.id,
53
27
  function: {
54
- name: history.operation.name,
55
- arguments: JSON.stringify(history.arguments),
28
+ name: `${history.type}Functions`,
29
+ arguments: JSON.stringify({
30
+ functions: history.selections.map(s => ({
31
+ name: s.operation.function.name,
32
+ reason: s.reason,
33
+ })),
34
+ }),
56
35
  },
57
36
  },
58
37
  ],
@@ -60,29 +39,54 @@ export namespace ChatGptHistoryDecoder {
60
39
  {
61
40
  role: "tool",
62
41
  tool_call_id: history.id,
63
- content: JSON.stringify({
42
+ content: "",
43
+ },
44
+ ];
45
+ }
46
+
47
+ return [
48
+ {
49
+ role: "assistant",
50
+ tool_calls: [
51
+ {
52
+ type: "function",
53
+ id: history.id,
64
54
  function: {
65
- protocol: history.operation.protocol,
66
- description: history.operation.function.description,
67
- parameters: history.operation.function.parameters,
68
- output: history.operation.function.output,
69
- ...(history.operation.protocol === "http"
70
- ? {
71
- method: history.operation.function.method,
72
- path: history.operation.function.path,
73
- }
74
- : {}),
55
+ name: history.operation.name,
56
+ arguments: JSON.stringify(history.arguments),
75
57
  },
58
+ },
59
+ ],
60
+ },
61
+ {
62
+ role: "tool",
63
+ tool_call_id: history.id,
64
+ content: JSON.stringify({
65
+ function: {
66
+ protocol: history.operation.protocol,
67
+ description: history.operation.function.description,
68
+ parameters: history.operation.function.parameters,
69
+ output: history.operation.function.output,
76
70
  ...(history.operation.protocol === "http"
77
71
  ? {
78
- status: history.value.status,
79
- data: history.value.body,
72
+ method: history.operation.function.method,
73
+ path: history.operation.function.path,
80
74
  }
81
- : {
82
- value: history.value,
83
- }),
84
- }),
85
- },
86
- ];
87
- };
75
+ : {}),
76
+ },
77
+ ...(history.operation.protocol === "http"
78
+ ? {
79
+ status: (history.value as IHttpResponse).status,
80
+ data: (history.value as IHttpResponse).body,
81
+ }
82
+ : {
83
+ value: history.value,
84
+ }),
85
+ }),
86
+ },
87
+ ];
88
88
  }
89
+
90
+ export const ChatGptHistoryDecoder = {
91
+ decode,
92
+ };