@agentica/core 0.8.3-dev.20250227 → 0.8.3

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 (46) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +404 -404
  3. package/package.json +1 -1
  4. package/prompts/cancel.md +4 -4
  5. package/prompts/common.md +2 -2
  6. package/prompts/describe.md +6 -6
  7. package/prompts/execute.md +6 -6
  8. package/prompts/initialize.md +2 -2
  9. package/prompts/select.md +6 -6
  10. package/src/Agentica.ts +318 -318
  11. package/src/chatgpt/ChatGptAgent.ts +71 -71
  12. package/src/chatgpt/ChatGptCallFunctionAgent.ts +445 -445
  13. package/src/chatgpt/ChatGptCancelFunctionAgent.ts +283 -283
  14. package/src/chatgpt/ChatGptDescribeFunctionAgent.ts +51 -51
  15. package/src/chatgpt/ChatGptHistoryDecoder.ts +87 -87
  16. package/src/chatgpt/ChatGptInitializeFunctionAgent.ts +88 -88
  17. package/src/chatgpt/ChatGptSelectFunctionAgent.ts +318 -318
  18. package/src/functional/createHttpLlmApplication.ts +63 -63
  19. package/src/index.ts +19 -19
  20. package/src/internal/AgenticaConstant.ts +4 -4
  21. package/src/internal/AgenticaDefaultPrompt.ts +39 -39
  22. package/src/internal/AgenticaOperationComposer.ts +82 -82
  23. package/src/internal/AgenticaPromptFactory.ts +30 -30
  24. package/src/internal/AgenticaPromptTransformer.ts +83 -83
  25. package/src/internal/AgenticaTokenUsageAggregator.ts +115 -115
  26. package/src/internal/MathUtil.ts +3 -3
  27. package/src/internal/Singleton.ts +22 -22
  28. package/src/internal/__map_take.ts +15 -15
  29. package/src/structures/IAgenticaConfig.ts +121 -121
  30. package/src/structures/IAgenticaContext.ts +128 -128
  31. package/src/structures/IAgenticaController.ts +130 -130
  32. package/src/structures/IAgenticaEvent.ts +224 -224
  33. package/src/structures/IAgenticaExecutor.ts +152 -152
  34. package/src/structures/IAgenticaOperation.ts +64 -64
  35. package/src/structures/IAgenticaOperationCollection.ts +50 -50
  36. package/src/structures/IAgenticaOperationSelection.ts +69 -69
  37. package/src/structures/IAgenticaPrompt.ts +173 -173
  38. package/src/structures/IAgenticaProps.ts +64 -64
  39. package/src/structures/IAgenticaProvider.ts +45 -45
  40. package/src/structures/IAgenticaSystemPrompt.ts +122 -122
  41. package/src/structures/IAgenticaTokenUsage.ts +107 -107
  42. package/src/structures/internal/__IChatCancelFunctionsApplication.ts +23 -23
  43. package/src/structures/internal/__IChatFunctionReference.ts +21 -21
  44. package/src/structures/internal/__IChatInitialApplication.ts +15 -15
  45. package/src/structures/internal/__IChatSelectFunctionsApplication.ts +24 -24
  46. package/src/typings/AgenticaSource.ts +6 -6
package/README.md CHANGED
@@ -1,404 +1,404 @@
1
- # `@agentica/core`
2
- ![agentica-conceptual-diagram](https://github.com/user-attachments/assets/d7ebbd1f-04d3-4b0d-9e2a-234e29dd6c57)
3
-
4
- [![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/wrtnlabs/agentica/blob/master/LICENSE)
5
- [![npm version](https://img.shields.io/npm/v/@agentica/core.svg)](https://www.npmjs.com/package/@agentica/core)
6
- [![Downloads](https://img.shields.io/npm/dm/@agentica/core.svg)](https://www.npmjs.com/package/@agentica/core)
7
- [![Build Status](https://github.com/wrtnlabs/agentica/workflows/build/badge.svg)](https://github.com/wrtnlabs/agentica/actions?query=workflow%3Abuild)
8
-
9
- The simplest **Agentic AI Library**, specialized in **LLM Function Calling**.
10
-
11
- `@agentica/core` is the simplest library specialized for LLM (Large Language Model) function calling. You can provide functions to call by *Swagger/OpenAPI* document or *TypeScript class type*, and it will make everything possible. *Super AI Chatbot* development, or *Multi Agent Orchestration*, all of them can be realized by the function calling.
12
-
13
- For example, if you provide **Swagger document** of a Shopping Mall Server, `@agentica/core` will compose **Super AI Chatbot** application. In the chatbot application, customers can purchase products just by conversation texts. If you wanna automate the counseling or refunding process, you also can do it just by delivering the Swagger document.
14
-
15
- Also, the LLM function calling strategy is effective for the **Multi-Agent Orchestration**, and it is easier to develop than any other way. You don't need to learn any complicate framework and its specific paradigms and patterns. Just connect them through class, and deliver the **TypeScript class type**. `@agentica/agentica` will centralize and realize the multi-agent orchestration through function calling.
16
-
17
- > https://github.com/user-attachments/assets/01604b53-aca4-41cb-91aa-3faf63549ea6
18
- >
19
- > Demonstration video of Shopping AI Chatbot
20
-
21
-
22
-
23
-
24
- ## How to Use
25
- ### Setup
26
- ```bash
27
- npm install @agentica/core @samchon/openapi typia
28
- npx typia setup
29
- ```
30
-
31
- Install not only `@agentica/core`, but also [`@samchon/openapi`](https://github.com/samchon/openapi) and [`typia`](https://github.com/samchon/typia).
32
-
33
- `@samchon/openapi` is an OpenAPI specification library which can convert Swagger/OpenAPI document to LLM function calling schema. And `typia` is a transformer (compiler) library which can compose LLM function calling schema from a TypeScript class type.
34
-
35
- By the way, as `typia` is a transformer library analyzing TypeScript source code in the compilation level, it needs additional setup command `npx typia setup`. Also, if you're not using non-standard TypeScript compiler (not `tsc`) or developing the agent in the frontend environment, you have to setup [`@ryoppippi/unplugin-typia`](https://typia.io/docs/setup/#unplugin-typia) too.
36
-
37
- ### Chat with Backend Server
38
- ```typescript
39
- import { IHttpLlmApplication } from "@samchon/openapi";
40
- import { Agentica, createHttpApplication } from "@agentica/core";
41
- import OpenAI from "openai";
42
- import { IValidation } from "typia";
43
-
44
- const main = async (): Promise<void> => {
45
- // LOAD SWAGGER DOCUMENT, AND CONVERT TO LLM APPLICATION SCHEMA
46
- const application: IValidation<IHttpLlmApplication<"chatgpt">> =
47
- createHttpApplication({
48
- model: "chatgpt",
49
- document: OpenApi.convert(
50
- await fetch("https://shopping-be.wrtn.ai/editor/swagger.json").then(
51
- (r) => r.json()
52
- )
53
- ),
54
- });
55
- if (application.success === false) {
56
- console.error(application.errors);
57
- throw new Error("Type error on the target swagger document");
58
- }
59
-
60
- // CREATE AN AGENT WITH THE APPLICATION
61
- const agent: Agentica = new Agentica({
62
- provider: {
63
- type: "chatgpt",
64
- model: "gpt-4o-mini",
65
- api: new OpenAI({
66
- apiKey: "YOUR_OPENAI_API_KEY",
67
- }),
68
- },
69
- controllers: [
70
- {
71
- protocol: "http",
72
- name: "shopping",
73
- application: application.data,
74
- connection: {
75
- host: "https://shopping-be.wrtn.ai",
76
- },
77
- },
78
- ],
79
- config: {
80
- locale: "en-US",
81
- },
82
- });
83
-
84
- // ADD EVENT LISTENERS
85
- agent.on("select", async (select) => {
86
- console.log("selected function", select.operation.function.name);
87
- });
88
- agent.on("execute", async (execute) => {
89
- consoe.log("execute function", {
90
- function: execute.operation.function.name,
91
- arguments: execute.arguments,
92
- value: execute.value,
93
- });
94
- });
95
-
96
- // CONVERSATE TO AI CHATBOT
97
- await agent.conversate("What you can do?");
98
- };
99
- main().catch(console.error);
100
- ```
101
-
102
- Just load your swagger document, and put it into the `@agentica/core`.
103
-
104
- Then you can start conversation with your backend server, and the API functions of the backend server would be automatically called. AI chatbot will analyze your conversation texts, and executes proper API functions by the LLM (Large Language Model) function calling feature.
105
-
106
- From now on, every backend developer is also an AI developer.
107
-
108
- ### Chat with TypeScript Class
109
- ```typescript
110
- import { Agentica } from "@agentica/core";
111
- import typia, { tags } from "typia";
112
- import OpenAI from "openai";
113
-
114
- class BbsArticleService {
115
- /**
116
- * Create a new article.
117
- *
118
- * Writes a new article and archives it into the DB.
119
- *
120
- * @param props Properties of create function
121
- * @returns Newly created article
122
- */
123
- public async create(props: {
124
- /**
125
- * Information of the article to create
126
- */
127
- input: IBbsArticle.ICreate;
128
- }): Promise<IBbsArticle>;
129
-
130
- /**
131
- * Update an article.
132
- *
133
- * Updates an article with new content.
134
- *
135
- * @param props Properties of update function
136
- * @param input New content to update
137
- */
138
- public async update(props: {
139
- /**
140
- * Target article's {@link IBbsArticle.id}.
141
- */
142
- id: string & tags.Format<"uuid">;
143
-
144
- /**
145
- * New content to update.
146
- */
147
- input: IBbsArticle.IUpdate;
148
- }): Promise<void>;
149
- }
150
-
151
- const main = async (): Promise<void> => {
152
- const api: OpenAI = new OpenAI({
153
- apiKey: "YOUR_OPENAI_API_KEY",
154
- });
155
- const agent: Agentica = new Agentica({
156
- provider: {
157
- type: "chatgpt",
158
- model: "gpt-4o-mini",
159
- api: new OpenAI({
160
- apiKey: "YOUR_OPENAI_API_KEY",
161
- }),
162
- },
163
- controllers: [
164
- {
165
- protocol: "class",
166
- name: "vectorStore",
167
- application: typia.llm.applicationOfValidate<
168
- BbsArticleService,
169
- "chatgpt"
170
- >(),
171
- execute: new BbsArticleService(),
172
- },
173
- ],
174
- });
175
- await agent.conversate("I wanna write an article.");
176
- };
177
- main().catch(console.error);
178
- ```
179
-
180
- You also can chat with a TypeScript class.
181
-
182
- Just deliver the TypeScript type to the `@agentica/core`, and start conversation. Then `@agentica/core` will call the proper class functions by analyzing your conversation texts with LLM function calling feature.
183
-
184
- From now on, every TypeScript classes you've developed can be the AI chatbot.
185
-
186
- ### Multi Agent Orchestration
187
- ```typescript
188
- import { Agentica } from "@agentica/core";
189
- import typia from "typia";
190
- import OpenAI from "openai";
191
-
192
- class OpenAIVectorStoreAgent {
193
- /**
194
- * Retrieve Vector DB with RAG.
195
- *
196
- * @param props Properties of Vector DB retrievelance
197
- */
198
- public query(props: {
199
- /**
200
- * Keywords to look up.
201
- *
202
- * Put all the keywords you want to look up. However, keywords
203
- * should only be included in the core, and all ambiguous things
204
- * should be excluded to achieve accurate results.
205
- */
206
- keywords: string;
207
- }): Promise<IVectorStoreQueryResult>;
208
- }
209
-
210
- const main = async (): Promise<void> => {
211
- const api: OpenAI = new OpenAI({
212
- apiKey: "YOUR_OPENAI_API_KEY",
213
- });
214
- const agent: Agentica = new Agentica({
215
- provider: {
216
- type: "chatgpt",
217
- model: "gpt-4o-mini",
218
- api: new OpenAI({
219
- apiKey: "YOUR_OPENAI_API_KEY",
220
- }),
221
- },
222
- controllers: [
223
- {
224
- protocol: "class",
225
- name: "vectorStore",
226
- application: typia.llm.applicationOfValidate<
227
- OpenAIVectorStoreAgent,
228
- "chatgpt"
229
- >(),
230
- execute: new OpenAIVectorStoreAgent({
231
- api,
232
- id: "YOUR_OPENAI_VECTOR_STORE_ID",
233
- }),
234
- },
235
- ],
236
- });
237
- await agent.conversate("I wanna research economic articles");
238
- };
239
- main().catch(console.error);
240
- ```
241
-
242
- In the `@agentica/core`, you can implement multi-agent orchestration super easily.
243
-
244
- Just develop a TypeScript class which contains agent feature like Vector Store, and just deliver the TypeScript class type to the `@agentica/core` like above. The `@agentica/core` will centralize and realize the multi-agent orchestration by LLM function calling strategy to the TypeScript class.
245
-
246
-
247
-
248
-
249
- ## Principles
250
- ### Agent Strategy
251
- ```mermaid
252
- sequenceDiagram
253
- actor User
254
- actor Agent
255
- participant Selector
256
- participant Caller
257
- participant Describer
258
- activate User
259
- User-->>Agent: Conversate:<br/>user says
260
- activate Agent
261
- Agent->>Selector: Deliver conversation text
262
- activate Selector
263
- deactivate User
264
- Note over Selector: Select or remove candidate functions
265
- alt No candidate
266
- Selector->>Agent: Talk like plain ChatGPT
267
- deactivate Selector
268
- Agent->>User: Conversate:<br/>agent says
269
- activate User
270
- deactivate User
271
- end
272
- deactivate Agent
273
- loop Candidate functions exist
274
- activate Agent
275
- Agent->>Caller: Deliver conversation text
276
- activate Caller
277
- alt Contexts are enough
278
- Note over Caller: Call fulfilled functions
279
- Caller->>Describer: Function call histories
280
- deactivate Caller
281
- activate Describer
282
- Describer->>Agent: Describe function calls
283
- deactivate Describer
284
- Agent->>User: Conversate:<br/>agent describes
285
- activate User
286
- deactivate User
287
- else Contexts are not enough
288
- break
289
- Caller->>Agent: Request more information
290
- end
291
- Agent->>User: Conversate:<br/>agent requests
292
- activate User
293
- deactivate User
294
- end
295
- deactivate Agent
296
- end
297
- ```
298
-
299
- When user says, `@agentica/core` delivers the conversation text to the `selector` agent, and let the `selector` agent to find (or cancel) candidate functions from the context. If the `selector` agent could not find any candidate function to call and there is not any candidate function previously selected either, the `selector` agent will work just like a plain ChatGPT.
300
-
301
- And `@agentica/core` enters to a loop statement until the candidate functions to be empty. In the loop statement, `caller` agent tries to LLM function calling by analyzing the user's conversation text. If context is enough to compose arguments of candidate functions, the `caller` agent actually calls the target functions, and let `decriber` agent to explain the function calling results. Otherwise the context is not enough to compose arguments, `caller` agent requests more information to user.
302
-
303
- Such LLM (Large Language Model) function calling strategy separating `selector`, `caller`, and `describer` is the key logic of `@agentica/core`.
304
-
305
- ### Validation Feedback
306
- ```typescript
307
- import { FunctionCall } from "pseudo";
308
- import { ILlmFunctionOfValidate, IValidation } from "typia";
309
-
310
- export const correctFunctionCall = (p: {
311
- call: FunctionCall;
312
- functions: Array<ILlmFunctionOfValidate<"chatgpt">>;
313
- retry: (reason: string, errors?: IValidation.IError[]) => Promise<unknown>;
314
- }): Promise<unknown> => {
315
- // FIND FUNCTION
316
- const func: ILlmFunctionOfValidate<"chatgpt"> | undefined =
317
- p.functions.find((f) => f.name === p.call.name);
318
- if (func === undefined) {
319
- // never happened in my experience
320
- return p.retry(
321
- "Unable to find the matched function name. Try it again.",
322
- );
323
- }
324
-
325
- // VALIDATE
326
- const result: IValidation<unknown> = func.validate(p.call.arguments);
327
- if (result.success === false) {
328
- // 1st trial: 50% (gpt-4o-mini in shopping mall chatbot)
329
- // 2nd trial with validation feedback: 99%
330
- // 3nd trial with validation feedback again: never have failed
331
- return p.retry(
332
- "Type errors are detected. Correct it through validation errors",
333
- {
334
- errors: result.errors,
335
- },
336
- );
337
- }
338
- return result.data;
339
- }
340
- ```
341
-
342
- Is LLM function calling perfect?
343
-
344
- The answer is not, and LLM (Large Language Model) providers like OpenAI take a lot of type level mistakes when composing the arguments of the target function to call. Even though an LLM function calling schema has defined an `Array<string>` type, LLM often fills it just by a `string` typed value.
345
-
346
- Therefore, when developing an LLM function calling agent, the validation feedback process is essentially required. If LLM takes a type level mistake on arguments composition, the agent must feedback the most detailed validation errors, and let the LLM to retry the function calling referencing the validation errors.
347
-
348
- About the validation feedback, `@agentica/core` is utilizing [`typia.validate<T>()`](https://typia.io/docs/validators/validate) and [`typia.llm.applicationOfValidate<Class, Model>()`](https://typia.io/docs/llm/application/#applicationofvalidate) functions. They construct validation logic by analyzing TypeScript source codes and types in the compilation level, so that detailed and accurate than any other validators like below.
349
-
350
- Such validation feedback strategy and combination with `typia` runtime validator, `@agentica/core` has achieved the most ideal LLM function calling. In my experience, when using OpenAI's `gpt-4o-mini` model, it tends to construct invalid function calling arguments at the first trial about 50% of the time. By the way, if correct it through validation feedback with `typia`, success rate soars to 99%. And I've never had a failure when trying validation feedback twice.
351
-
352
- Components | `typia` | `TypeBox` | `ajv` | `io-ts` | `zod` | `C.V.`
353
- -------------------------|--------|-----------|-------|---------|-------|------------------
354
- **Easy to use** | ✅ | ❌ | ❌ | ❌ | ❌ | ❌
355
- [Object (simple)](https://github.com/samchon/typia/blob/master/test/src/structures/ObjectSimple.ts) | ✔ | ✔ | ✔ | ✔ | ✔ | ✔
356
- [Object (hierarchical)](https://github.com/samchon/typia/blob/master/test/src/structures/ObjectHierarchical.ts) | ✔ | ✔ | ✔ | ✔ | ✔ | ✔
357
- [Object (recursive)](https://github.com/samchon/typia/blob/master/test/src/structures/ObjectRecursive.ts) | ✔ | ❌ | ✔ | ✔ | ✔ | ✔ | ✔
358
- [Object (union, implicit)](https://github.com/samchon/typia/blob/master/test/src/structures/ObjectUnionImplicit.ts) | ✅ | ❌ | ❌ | ❌ | ❌ | ❌
359
- [Object (union, explicit)](https://github.com/samchon/typia/blob/master/test/src/structures/ObjectUnionExplicit.ts) | ✔ | ✔ | ✔ | ✔ | ✔ | ❌
360
- [Object (additional tags)](https://github.com/samchon/typia/#comment-tags) | ✔ | ✔ | ✔ | ✔ | ✔ | ✔
361
- [Object (template literal types)](https://github.com/samchon/typia/blob/master/test/src/structures/TemplateUnion.ts) | ✔ | ✔ | ✔ | ❌ | ❌ | ❌
362
- [Object (dynamic properties)](https://github.com/samchon/typia/blob/master/test/src/structures/DynamicTemplate.ts) | ✔ | ✔ | ✔ | ❌ | ❌ | ❌
363
- [Array (rest tuple)](https://github.com/samchon/typia/blob/master/test/src/structures/TupleRestAtomic.ts) | ✅ | ❌ | ❌ | ❌ | ❌ | ❌
364
- [Array (hierarchical)](https://github.com/samchon/typia/blob/master/test/src/structures/ArrayHierarchical.ts) | ✔ | ✔ | ✔ | ✔ | ✔ | ✔
365
- [Array (recursive)](https://github.com/samchon/typia/blob/master/test/src/structures/ArrayRecursive.ts) | ✔ | ✔ | ✔ | ✔ | ✔ | ❌
366
- [Array (recursive, union)](https://github.com/samchon/typia/blob/master/test/src/structures/ArrayRecursiveUnionExplicit.ts) | ✔ | ✔ | ❌ | ✔ | ✔ | ❌
367
- [Array (R+U, implicit)](https://github.com/samchon/typia/blob/master/test/src/structures/ArrayRecursiveUnionImplicit.ts) | ✅ | ❌ | ❌ | ❌ | ❌ | ❌
368
- [Array (repeated)](https://github.com/samchon/typia/blob/master/test/src/structures/ArrayRepeatedNullable.ts) | ✅ | ❌ | ❌ | ❌ | ❌ | ❌
369
- [Array (repeated, union)](https://github.com/samchon/typia/blob/master/test/src/structures/ArrayRepeatedUnionWithTuple.ts) | ✅ | ❌ | ❌ | ❌ | ❌ | ❌
370
- [**Ultimate Union Type**](https://github.com/samchon/typia/blob/master/test/src/structures/UltimateUnion.ts) | ✅ | ❌ | ❌ | ❌ | ❌ | ❌
371
-
372
- > `C.V.` means `class-validator`
373
-
374
- ### OpenAPI Specification
375
- ```mermaid
376
- flowchart
377
- subgraph "OpenAPI Specification"
378
- v20("Swagger v2.0") --upgrades--> emended[["OpenAPI v3.1 (emended)"]]
379
- v30("OpenAPI v3.0") --upgrades--> emended
380
- v31("OpenAPI v3.1") --emends--> emended
381
- end
382
- subgraph "OpenAPI Generator"
383
- emended --normalizes--> migration[["Migration Schema"]]
384
- migration --"Artificial Intelligence"--> lfc{{"LLM Function Calling"}}
385
- lfc --"OpenAI"--> chatgpt("ChatGPT")
386
- lfc --"Anthropic"--> claude("Claude")
387
- lfc --"Google"--> gemini("Gemini")
388
- lfc --"Meta"--> llama("Llama")
389
- end
390
- ```
391
-
392
- `@agentica/core` obtains LLM function calling schemas from both Swagger/OpenAPI documents and TypeScript class types. The TypeScript class type can be converted to LLM function calling schema by [`typia.llm.applicationOfValidate<Class, Model>()`](https://typia.io/docs/llm/application#applicationofvalidate) function. Then how about OpenAPI document? How Swagger document can be LLM function calling schema.
393
-
394
- The secret is on the above diagram.
395
-
396
- In the OpenAPI specification, there are three versions with different definitions. And even in the same version, there are too much ambiguous and duplicated expressions. To resolve these problems, [`@samchon/openapi`](https://github.com/samchon/openapi) is transforming every OpenAPI documents to v3.1 emended specification. The `@samchon/openapi`'s emended v3.1 specification has removed every ambiguous and duplicated expressions for clarity.
397
-
398
- With the v3.1 emended OpenAPI document, `@samchon/openapi` converts it to a migration schema that is near to the function structure. And as the last step, the migration schema will be transformed to a specific LLM provider's function calling schema. LLM function calling schemas are composed like this way.
399
-
400
- > **Why do not directly convert, but intermediate?**
401
- >
402
- > If directly convert from each version of OpenAPI specification to specific LLM's function calling schema, I have to make much more converters increased by cartesian product. In current models, number of converters would be 12 = 3 x 4.
403
- >
404
- > However, if define intermediate schema, number of converters are shrunk to plus operation. In current models, I just need to develop only (7 = 3 + 4) converters, and this is the reason why I've defined intermediate specification. This way is economic.
1
+ # `@agentica/core`
2
+ ![agentica-conceptual-diagram](https://github.com/user-attachments/assets/d7ebbd1f-04d3-4b0d-9e2a-234e29dd6c57)
3
+
4
+ [![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/wrtnlabs/agentica/blob/master/LICENSE)
5
+ [![npm version](https://img.shields.io/npm/v/@agentica/core.svg)](https://www.npmjs.com/package/@agentica/core)
6
+ [![Downloads](https://img.shields.io/npm/dm/@agentica/core.svg)](https://www.npmjs.com/package/@agentica/core)
7
+ [![Build Status](https://github.com/wrtnlabs/agentica/workflows/build/badge.svg)](https://github.com/wrtnlabs/agentica/actions?query=workflow%3Abuild)
8
+
9
+ The simplest **Agentic AI Library**, specialized in **LLM Function Calling**.
10
+
11
+ `@agentica/core` is the simplest library specialized for LLM (Large Language Model) function calling. You can provide functions to call by *Swagger/OpenAPI* document or *TypeScript class type*, and it will make everything possible. *Super AI Chatbot* development, or *Multi Agent Orchestration*, all of them can be realized by the function calling.
12
+
13
+ For example, if you provide **Swagger document** of a Shopping Mall Server, `@agentica/core` will compose **Super AI Chatbot** application. In the chatbot application, customers can purchase products just by conversation texts. If you wanna automate the counseling or refunding process, you also can do it just by delivering the Swagger document.
14
+
15
+ Also, the LLM function calling strategy is effective for the **Multi-Agent Orchestration**, and it is easier to develop than any other way. You don't need to learn any complicate framework and its specific paradigms and patterns. Just connect them through class, and deliver the **TypeScript class type**. `@agentica/agentica` will centralize and realize the multi-agent orchestration through function calling.
16
+
17
+ > https://github.com/user-attachments/assets/01604b53-aca4-41cb-91aa-3faf63549ea6
18
+ >
19
+ > Demonstration video of Shopping AI Chatbot
20
+
21
+
22
+
23
+
24
+ ## How to Use
25
+ ### Setup
26
+ ```bash
27
+ npm install @agentica/core @samchon/openapi typia
28
+ npx typia setup
29
+ ```
30
+
31
+ Install not only `@agentica/core`, but also [`@samchon/openapi`](https://github.com/samchon/openapi) and [`typia`](https://github.com/samchon/typia).
32
+
33
+ `@samchon/openapi` is an OpenAPI specification library which can convert Swagger/OpenAPI document to LLM function calling schema. And `typia` is a transformer (compiler) library which can compose LLM function calling schema from a TypeScript class type.
34
+
35
+ By the way, as `typia` is a transformer library analyzing TypeScript source code in the compilation level, it needs additional setup command `npx typia setup`. Also, if you're not using non-standard TypeScript compiler (not `tsc`) or developing the agent in the frontend environment, you have to setup [`@ryoppippi/unplugin-typia`](https://typia.io/docs/setup/#unplugin-typia) too.
36
+
37
+ ### Chat with Backend Server
38
+ ```typescript
39
+ import { IHttpLlmApplication } from "@samchon/openapi";
40
+ import { Agentica, createHttpApplication } from "@agentica/core";
41
+ import OpenAI from "openai";
42
+ import { IValidation } from "typia";
43
+
44
+ const main = async (): Promise<void> => {
45
+ // LOAD SWAGGER DOCUMENT, AND CONVERT TO LLM APPLICATION SCHEMA
46
+ const application: IValidation<IHttpLlmApplication<"chatgpt">> =
47
+ createHttpApplication({
48
+ model: "chatgpt",
49
+ document: OpenApi.convert(
50
+ await fetch("https://shopping-be.wrtn.ai/editor/swagger.json").then(
51
+ (r) => r.json()
52
+ )
53
+ ),
54
+ });
55
+ if (application.success === false) {
56
+ console.error(application.errors);
57
+ throw new Error("Type error on the target swagger document");
58
+ }
59
+
60
+ // CREATE AN AGENT WITH THE APPLICATION
61
+ const agent: Agentica = new Agentica({
62
+ provider: {
63
+ type: "chatgpt",
64
+ model: "gpt-4o-mini",
65
+ api: new OpenAI({
66
+ apiKey: "YOUR_OPENAI_API_KEY",
67
+ }),
68
+ },
69
+ controllers: [
70
+ {
71
+ protocol: "http",
72
+ name: "shopping",
73
+ application: application.data,
74
+ connection: {
75
+ host: "https://shopping-be.wrtn.ai",
76
+ },
77
+ },
78
+ ],
79
+ config: {
80
+ locale: "en-US",
81
+ },
82
+ });
83
+
84
+ // ADD EVENT LISTENERS
85
+ agent.on("select", async (select) => {
86
+ console.log("selected function", select.operation.function.name);
87
+ });
88
+ agent.on("execute", async (execute) => {
89
+ consoe.log("execute function", {
90
+ function: execute.operation.function.name,
91
+ arguments: execute.arguments,
92
+ value: execute.value,
93
+ });
94
+ });
95
+
96
+ // CONVERSATE TO AI CHATBOT
97
+ await agent.conversate("What you can do?");
98
+ };
99
+ main().catch(console.error);
100
+ ```
101
+
102
+ Just load your swagger document, and put it into the `@agentica/core`.
103
+
104
+ Then you can start conversation with your backend server, and the API functions of the backend server would be automatically called. AI chatbot will analyze your conversation texts, and executes proper API functions by the LLM (Large Language Model) function calling feature.
105
+
106
+ From now on, every backend developer is also an AI developer.
107
+
108
+ ### Chat with TypeScript Class
109
+ ```typescript
110
+ import { Agentica } from "@agentica/core";
111
+ import typia, { tags } from "typia";
112
+ import OpenAI from "openai";
113
+
114
+ class BbsArticleService {
115
+ /**
116
+ * Create a new article.
117
+ *
118
+ * Writes a new article and archives it into the DB.
119
+ *
120
+ * @param props Properties of create function
121
+ * @returns Newly created article
122
+ */
123
+ public async create(props: {
124
+ /**
125
+ * Information of the article to create
126
+ */
127
+ input: IBbsArticle.ICreate;
128
+ }): Promise<IBbsArticle>;
129
+
130
+ /**
131
+ * Update an article.
132
+ *
133
+ * Updates an article with new content.
134
+ *
135
+ * @param props Properties of update function
136
+ * @param input New content to update
137
+ */
138
+ public async update(props: {
139
+ /**
140
+ * Target article's {@link IBbsArticle.id}.
141
+ */
142
+ id: string & tags.Format<"uuid">;
143
+
144
+ /**
145
+ * New content to update.
146
+ */
147
+ input: IBbsArticle.IUpdate;
148
+ }): Promise<void>;
149
+ }
150
+
151
+ const main = async (): Promise<void> => {
152
+ const api: OpenAI = new OpenAI({
153
+ apiKey: "YOUR_OPENAI_API_KEY",
154
+ });
155
+ const agent: Agentica = new Agentica({
156
+ provider: {
157
+ type: "chatgpt",
158
+ model: "gpt-4o-mini",
159
+ api: new OpenAI({
160
+ apiKey: "YOUR_OPENAI_API_KEY",
161
+ }),
162
+ },
163
+ controllers: [
164
+ {
165
+ protocol: "class",
166
+ name: "vectorStore",
167
+ application: typia.llm.applicationOfValidate<
168
+ BbsArticleService,
169
+ "chatgpt"
170
+ >(),
171
+ execute: new BbsArticleService(),
172
+ },
173
+ ],
174
+ });
175
+ await agent.conversate("I wanna write an article.");
176
+ };
177
+ main().catch(console.error);
178
+ ```
179
+
180
+ You also can chat with a TypeScript class.
181
+
182
+ Just deliver the TypeScript type to the `@agentica/core`, and start conversation. Then `@agentica/core` will call the proper class functions by analyzing your conversation texts with LLM function calling feature.
183
+
184
+ From now on, every TypeScript classes you've developed can be the AI chatbot.
185
+
186
+ ### Multi Agent Orchestration
187
+ ```typescript
188
+ import { Agentica } from "@agentica/core";
189
+ import typia from "typia";
190
+ import OpenAI from "openai";
191
+
192
+ class OpenAIVectorStoreAgent {
193
+ /**
194
+ * Retrieve Vector DB with RAG.
195
+ *
196
+ * @param props Properties of Vector DB retrievelance
197
+ */
198
+ public query(props: {
199
+ /**
200
+ * Keywords to look up.
201
+ *
202
+ * Put all the keywords you want to look up. However, keywords
203
+ * should only be included in the core, and all ambiguous things
204
+ * should be excluded to achieve accurate results.
205
+ */
206
+ keywords: string;
207
+ }): Promise<IVectorStoreQueryResult>;
208
+ }
209
+
210
+ const main = async (): Promise<void> => {
211
+ const api: OpenAI = new OpenAI({
212
+ apiKey: "YOUR_OPENAI_API_KEY",
213
+ });
214
+ const agent: Agentica = new Agentica({
215
+ provider: {
216
+ type: "chatgpt",
217
+ model: "gpt-4o-mini",
218
+ api: new OpenAI({
219
+ apiKey: "YOUR_OPENAI_API_KEY",
220
+ }),
221
+ },
222
+ controllers: [
223
+ {
224
+ protocol: "class",
225
+ name: "vectorStore",
226
+ application: typia.llm.applicationOfValidate<
227
+ OpenAIVectorStoreAgent,
228
+ "chatgpt"
229
+ >(),
230
+ execute: new OpenAIVectorStoreAgent({
231
+ api,
232
+ id: "YOUR_OPENAI_VECTOR_STORE_ID",
233
+ }),
234
+ },
235
+ ],
236
+ });
237
+ await agent.conversate("I wanna research economic articles");
238
+ };
239
+ main().catch(console.error);
240
+ ```
241
+
242
+ In the `@agentica/core`, you can implement multi-agent orchestration super easily.
243
+
244
+ Just develop a TypeScript class which contains agent feature like Vector Store, and just deliver the TypeScript class type to the `@agentica/core` like above. The `@agentica/core` will centralize and realize the multi-agent orchestration by LLM function calling strategy to the TypeScript class.
245
+
246
+
247
+
248
+
249
+ ## Principles
250
+ ### Agent Strategy
251
+ ```mermaid
252
+ sequenceDiagram
253
+ actor User
254
+ actor Agent
255
+ participant Selector
256
+ participant Caller
257
+ participant Describer
258
+ activate User
259
+ User-->>Agent: Conversate:<br/>user says
260
+ activate Agent
261
+ Agent->>Selector: Deliver conversation text
262
+ activate Selector
263
+ deactivate User
264
+ Note over Selector: Select or remove candidate functions
265
+ alt No candidate
266
+ Selector->>Agent: Talk like plain ChatGPT
267
+ deactivate Selector
268
+ Agent->>User: Conversate:<br/>agent says
269
+ activate User
270
+ deactivate User
271
+ end
272
+ deactivate Agent
273
+ loop Candidate functions exist
274
+ activate Agent
275
+ Agent->>Caller: Deliver conversation text
276
+ activate Caller
277
+ alt Contexts are enough
278
+ Note over Caller: Call fulfilled functions
279
+ Caller->>Describer: Function call histories
280
+ deactivate Caller
281
+ activate Describer
282
+ Describer->>Agent: Describe function calls
283
+ deactivate Describer
284
+ Agent->>User: Conversate:<br/>agent describes
285
+ activate User
286
+ deactivate User
287
+ else Contexts are not enough
288
+ break
289
+ Caller->>Agent: Request more information
290
+ end
291
+ Agent->>User: Conversate:<br/>agent requests
292
+ activate User
293
+ deactivate User
294
+ end
295
+ deactivate Agent
296
+ end
297
+ ```
298
+
299
+ When user says, `@agentica/core` delivers the conversation text to the `selector` agent, and let the `selector` agent to find (or cancel) candidate functions from the context. If the `selector` agent could not find any candidate function to call and there is not any candidate function previously selected either, the `selector` agent will work just like a plain ChatGPT.
300
+
301
+ And `@agentica/core` enters to a loop statement until the candidate functions to be empty. In the loop statement, `caller` agent tries to LLM function calling by analyzing the user's conversation text. If context is enough to compose arguments of candidate functions, the `caller` agent actually calls the target functions, and let `decriber` agent to explain the function calling results. Otherwise the context is not enough to compose arguments, `caller` agent requests more information to user.
302
+
303
+ Such LLM (Large Language Model) function calling strategy separating `selector`, `caller`, and `describer` is the key logic of `@agentica/core`.
304
+
305
+ ### Validation Feedback
306
+ ```typescript
307
+ import { FunctionCall } from "pseudo";
308
+ import { ILlmFunctionOfValidate, IValidation } from "typia";
309
+
310
+ export const correctFunctionCall = (p: {
311
+ call: FunctionCall;
312
+ functions: Array<ILlmFunctionOfValidate<"chatgpt">>;
313
+ retry: (reason: string, errors?: IValidation.IError[]) => Promise<unknown>;
314
+ }): Promise<unknown> => {
315
+ // FIND FUNCTION
316
+ const func: ILlmFunctionOfValidate<"chatgpt"> | undefined =
317
+ p.functions.find((f) => f.name === p.call.name);
318
+ if (func === undefined) {
319
+ // never happened in my experience
320
+ return p.retry(
321
+ "Unable to find the matched function name. Try it again.",
322
+ );
323
+ }
324
+
325
+ // VALIDATE
326
+ const result: IValidation<unknown> = func.validate(p.call.arguments);
327
+ if (result.success === false) {
328
+ // 1st trial: 50% (gpt-4o-mini in shopping mall chatbot)
329
+ // 2nd trial with validation feedback: 99%
330
+ // 3nd trial with validation feedback again: never have failed
331
+ return p.retry(
332
+ "Type errors are detected. Correct it through validation errors",
333
+ {
334
+ errors: result.errors,
335
+ },
336
+ );
337
+ }
338
+ return result.data;
339
+ }
340
+ ```
341
+
342
+ Is LLM function calling perfect?
343
+
344
+ The answer is not, and LLM (Large Language Model) providers like OpenAI take a lot of type level mistakes when composing the arguments of the target function to call. Even though an LLM function calling schema has defined an `Array<string>` type, LLM often fills it just by a `string` typed value.
345
+
346
+ Therefore, when developing an LLM function calling agent, the validation feedback process is essentially required. If LLM takes a type level mistake on arguments composition, the agent must feedback the most detailed validation errors, and let the LLM to retry the function calling referencing the validation errors.
347
+
348
+ About the validation feedback, `@agentica/core` is utilizing [`typia.validate<T>()`](https://typia.io/docs/validators/validate) and [`typia.llm.applicationOfValidate<Class, Model>()`](https://typia.io/docs/llm/application/#applicationofvalidate) functions. They construct validation logic by analyzing TypeScript source codes and types in the compilation level, so that detailed and accurate than any other validators like below.
349
+
350
+ Such validation feedback strategy and combination with `typia` runtime validator, `@agentica/core` has achieved the most ideal LLM function calling. In my experience, when using OpenAI's `gpt-4o-mini` model, it tends to construct invalid function calling arguments at the first trial about 50% of the time. By the way, if correct it through validation feedback with `typia`, success rate soars to 99%. And I've never had a failure when trying validation feedback twice.
351
+
352
+ Components | `typia` | `TypeBox` | `ajv` | `io-ts` | `zod` | `C.V.`
353
+ -------------------------|--------|-----------|-------|---------|-------|------------------
354
+ **Easy to use** | ✅ | ❌ | ❌ | ❌ | ❌ | ❌
355
+ [Object (simple)](https://github.com/samchon/typia/blob/master/test/src/structures/ObjectSimple.ts) | ✔ | ✔ | ✔ | ✔ | ✔ | ✔
356
+ [Object (hierarchical)](https://github.com/samchon/typia/blob/master/test/src/structures/ObjectHierarchical.ts) | ✔ | ✔ | ✔ | ✔ | ✔ | ✔
357
+ [Object (recursive)](https://github.com/samchon/typia/blob/master/test/src/structures/ObjectRecursive.ts) | ✔ | ❌ | ✔ | ✔ | ✔ | ✔ | ✔
358
+ [Object (union, implicit)](https://github.com/samchon/typia/blob/master/test/src/structures/ObjectUnionImplicit.ts) | ✅ | ❌ | ❌ | ❌ | ❌ | ❌
359
+ [Object (union, explicit)](https://github.com/samchon/typia/blob/master/test/src/structures/ObjectUnionExplicit.ts) | ✔ | ✔ | ✔ | ✔ | ✔ | ❌
360
+ [Object (additional tags)](https://github.com/samchon/typia/#comment-tags) | ✔ | ✔ | ✔ | ✔ | ✔ | ✔
361
+ [Object (template literal types)](https://github.com/samchon/typia/blob/master/test/src/structures/TemplateUnion.ts) | ✔ | ✔ | ✔ | ❌ | ❌ | ❌
362
+ [Object (dynamic properties)](https://github.com/samchon/typia/blob/master/test/src/structures/DynamicTemplate.ts) | ✔ | ✔ | ✔ | ❌ | ❌ | ❌
363
+ [Array (rest tuple)](https://github.com/samchon/typia/blob/master/test/src/structures/TupleRestAtomic.ts) | ✅ | ❌ | ❌ | ❌ | ❌ | ❌
364
+ [Array (hierarchical)](https://github.com/samchon/typia/blob/master/test/src/structures/ArrayHierarchical.ts) | ✔ | ✔ | ✔ | ✔ | ✔ | ✔
365
+ [Array (recursive)](https://github.com/samchon/typia/blob/master/test/src/structures/ArrayRecursive.ts) | ✔ | ✔ | ✔ | ✔ | ✔ | ❌
366
+ [Array (recursive, union)](https://github.com/samchon/typia/blob/master/test/src/structures/ArrayRecursiveUnionExplicit.ts) | ✔ | ✔ | ❌ | ✔ | ✔ | ❌
367
+ [Array (R+U, implicit)](https://github.com/samchon/typia/blob/master/test/src/structures/ArrayRecursiveUnionImplicit.ts) | ✅ | ❌ | ❌ | ❌ | ❌ | ❌
368
+ [Array (repeated)](https://github.com/samchon/typia/blob/master/test/src/structures/ArrayRepeatedNullable.ts) | ✅ | ❌ | ❌ | ❌ | ❌ | ❌
369
+ [Array (repeated, union)](https://github.com/samchon/typia/blob/master/test/src/structures/ArrayRepeatedUnionWithTuple.ts) | ✅ | ❌ | ❌ | ❌ | ❌ | ❌
370
+ [**Ultimate Union Type**](https://github.com/samchon/typia/blob/master/test/src/structures/UltimateUnion.ts) | ✅ | ❌ | ❌ | ❌ | ❌ | ❌
371
+
372
+ > `C.V.` means `class-validator`
373
+
374
+ ### OpenAPI Specification
375
+ ```mermaid
376
+ flowchart
377
+ subgraph "OpenAPI Specification"
378
+ v20("Swagger v2.0") --upgrades--> emended[["OpenAPI v3.1 (emended)"]]
379
+ v30("OpenAPI v3.0") --upgrades--> emended
380
+ v31("OpenAPI v3.1") --emends--> emended
381
+ end
382
+ subgraph "OpenAPI Generator"
383
+ emended --normalizes--> migration[["Migration Schema"]]
384
+ migration --"Artificial Intelligence"--> lfc{{"LLM Function Calling"}}
385
+ lfc --"OpenAI"--> chatgpt("ChatGPT")
386
+ lfc --"Anthropic"--> claude("Claude")
387
+ lfc --"Google"--> gemini("Gemini")
388
+ lfc --"Meta"--> llama("Llama")
389
+ end
390
+ ```
391
+
392
+ `@agentica/core` obtains LLM function calling schemas from both Swagger/OpenAPI documents and TypeScript class types. The TypeScript class type can be converted to LLM function calling schema by [`typia.llm.applicationOfValidate<Class, Model>()`](https://typia.io/docs/llm/application#applicationofvalidate) function. Then how about OpenAPI document? How Swagger document can be LLM function calling schema.
393
+
394
+ The secret is on the above diagram.
395
+
396
+ In the OpenAPI specification, there are three versions with different definitions. And even in the same version, there are too much ambiguous and duplicated expressions. To resolve these problems, [`@samchon/openapi`](https://github.com/samchon/openapi) is transforming every OpenAPI documents to v3.1 emended specification. The `@samchon/openapi`'s emended v3.1 specification has removed every ambiguous and duplicated expressions for clarity.
397
+
398
+ With the v3.1 emended OpenAPI document, `@samchon/openapi` converts it to a migration schema that is near to the function structure. And as the last step, the migration schema will be transformed to a specific LLM provider's function calling schema. LLM function calling schemas are composed like this way.
399
+
400
+ > **Why do not directly convert, but intermediate?**
401
+ >
402
+ > If directly convert from each version of OpenAPI specification to specific LLM's function calling schema, I have to make much more converters increased by cartesian product. In current models, number of converters would be 12 = 3 x 4.
403
+ >
404
+ > However, if define intermediate schema, number of converters are shrunk to plus operation. In current models, I just need to develop only (7 = 3 + 4) converters, and this is the reason why I've defined intermediate specification. This way is economic.