@ai.ntellect/core 0.5.0 → 0.6.1

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 (131) hide show
  1. package/.mocharc.json +1 -1
  2. package/README.md +311 -272
  3. package/create-llm-to-select-multiple-graph copy.ts +243 -0
  4. package/create-llm-to-select-multiple-graph.ts +148 -0
  5. package/dist/graph/controller.js +63 -0
  6. package/dist/graph/engine.js +563 -0
  7. package/dist/index.js +6 -6
  8. package/dist/memory/adapters/meilisearch/index.js +249 -0
  9. package/dist/memory/adapters/redis/index.js +96 -0
  10. package/dist/memory/index.js +9 -0
  11. package/dist/services/agenda.js +115 -0
  12. package/dist/services/embedding.js +40 -0
  13. package/dist/services/queue.js +99 -103
  14. package/dist/test/graph/controller.test.js +170 -0
  15. package/dist/test/graph/engine.test.js +465 -0
  16. package/dist/test/memory/adapters/meilisearch.test.js +250 -0
  17. package/dist/test/memory/adapters/redis.test.js +143 -0
  18. package/dist/test/memory/base.test.js +209 -0
  19. package/dist/test/services/agenda.test.js +230 -0
  20. package/dist/test/services/queue.test.js +258 -0
  21. package/dist/types/index.js +2 -0
  22. package/dist/utils/generate-object.js +32 -11
  23. package/dist/utils/inject-actions.js +2 -2
  24. package/dist/utils/queue-item-transformer.js +2 -2
  25. package/dist/utils/state-manager.js +20 -0
  26. package/graph/controller.ts +64 -0
  27. package/graph/engine.ts +790 -0
  28. package/index copy.ts +81 -0
  29. package/index.ts +7 -7
  30. package/interfaces/index.ts +119 -0
  31. package/memory/adapters/meilisearch/index.ts +286 -0
  32. package/memory/adapters/redis/index.ts +103 -0
  33. package/memory/index.ts +22 -0
  34. package/package.json +7 -2
  35. package/services/agenda.ts +48 -43
  36. package/services/embedding.ts +26 -0
  37. package/services/queue.ts +2 -29
  38. package/test/.env.test +4 -0
  39. package/test/graph/controller.test.ts +186 -0
  40. package/test/graph/engine.test.ts +546 -0
  41. package/test/memory/adapters/meilisearch.test.ts +297 -0
  42. package/test/memory/adapters/redis.test.ts +160 -0
  43. package/test/memory/base.test.ts +229 -0
  44. package/test/services/agenda.test.ts +280 -0
  45. package/test/services/queue.test.ts +286 -44
  46. package/tsconfig.json +10 -10
  47. package/types/index.ts +278 -0
  48. package/utils/queue-item-transformer.ts +8 -11
  49. package/utils/setup-graphs.ts +45 -0
  50. package/utils/stringifiy-zod-schema.ts +45 -0
  51. package/.nvmrc +0 -1
  52. package/README.FR.md +0 -916
  53. package/agent/index.ts +0 -151
  54. package/agent/workflow/conditions.ts +0 -16
  55. package/agent/workflow/handlers/interpreter.handler.ts +0 -48
  56. package/agent/workflow/handlers/memory.handler.ts +0 -106
  57. package/agent/workflow/handlers/orchestrator.handler.ts +0 -23
  58. package/agent/workflow/handlers/queue.handler.ts +0 -34
  59. package/agent/workflow/handlers/scheduler.handler.ts +0 -61
  60. package/agent/workflow/index.ts +0 -62
  61. package/dist/agent/index.d.ts +0 -38
  62. package/dist/agent/index.js +0 -143
  63. package/dist/agent/tools/get-rss.d.ts +0 -16
  64. package/dist/agent/tools/get-rss.js +0 -62
  65. package/dist/bull.d.ts +0 -1
  66. package/dist/bull.js +0 -9
  67. package/dist/examples/index.d.ts +0 -2
  68. package/dist/examples/index.js +0 -89
  69. package/dist/index.d.ts +0 -7
  70. package/dist/llm/interpreter/context.d.ts +0 -15
  71. package/dist/llm/interpreter/context.js +0 -89
  72. package/dist/llm/interpreter/index.d.ts +0 -21
  73. package/dist/llm/interpreter/index.js +0 -87
  74. package/dist/llm/memory-manager/context.d.ts +0 -2
  75. package/dist/llm/memory-manager/context.js +0 -22
  76. package/dist/llm/memory-manager/index.d.ts +0 -17
  77. package/dist/llm/memory-manager/index.js +0 -107
  78. package/dist/llm/orchestrator/context.d.ts +0 -2
  79. package/dist/llm/orchestrator/context.js +0 -23
  80. package/dist/llm/orchestrator/index.d.ts +0 -44
  81. package/dist/llm/orchestrator/index.js +0 -139
  82. package/dist/llm/orchestrator/types.d.ts +0 -12
  83. package/dist/memory/cache.d.ts +0 -22
  84. package/dist/memory/cache.js +0 -165
  85. package/dist/memory/persistent.d.ts +0 -57
  86. package/dist/memory/persistent.js +0 -189
  87. package/dist/services/queue.d.ts +0 -13
  88. package/dist/services/redis-cache.d.ts +0 -37
  89. package/dist/services/redis-cache.js +0 -93
  90. package/dist/services/scheduler.d.ts +0 -40
  91. package/dist/services/scheduler.js +0 -99
  92. package/dist/services/telegram-monitor.d.ts +0 -0
  93. package/dist/services/telegram-monitor.js +0 -118
  94. package/dist/t.d.ts +0 -46
  95. package/dist/t.js +0 -102
  96. package/dist/test.d.ts +0 -0
  97. package/dist/test.js +0 -438
  98. package/dist/types.d.ts +0 -258
  99. package/dist/types.js +0 -22
  100. package/dist/utils/generate-object.d.ts +0 -12
  101. package/dist/utils/header-builder.d.ts +0 -11
  102. package/dist/utils/inject-actions.d.ts +0 -2
  103. package/dist/utils/queue-item-transformer.d.ts +0 -7
  104. package/dist/utils/sanitize-results.d.ts +0 -17
  105. package/dist/utils/schema-generator.d.ts +0 -16
  106. package/examples/actions/get-rss.ts +0 -71
  107. package/examples/index.ts +0 -98
  108. package/index.html +0 -42
  109. package/llm/dynamic-condition/example.ts +0 -36
  110. package/llm/dynamic-condition/index.ts +0 -108
  111. package/llm/interpreter/context.ts +0 -94
  112. package/llm/interpreter/index.ts +0 -140
  113. package/llm/memory-manager/context.ts +0 -19
  114. package/llm/memory-manager/index.ts +0 -115
  115. package/llm/orchestrator/context.ts +0 -19
  116. package/llm/orchestrator/index.ts +0 -192
  117. package/llm/orchestrator/types.ts +0 -14
  118. package/memory/cache.ts +0 -221
  119. package/memory/persistent.ts +0 -265
  120. package/script.js +0 -167
  121. package/services/cache.ts +0 -298
  122. package/services/telegram-monitor.ts +0 -138
  123. package/services/workflow.ts +0 -491
  124. package/t.py +0 -79
  125. package/t.ts +0 -25
  126. package/test/llm/orchestrator.test.ts +0 -47
  127. package/test/llm/synthesizer.test.ts +0 -31
  128. package/types.ts +0 -367
  129. package/utils/schema-generator.ts +0 -73
  130. package/utils/state-manager.ts +0 -25
  131. /package/dist/{llm/orchestrator/types.js → interfaces/index.js} +0 -0
package/README.md CHANGED
@@ -1,365 +1,404 @@
1
- # AI.ntellect Core Framework
2
-
3
- ## Overview
4
-
5
- This framework is designed to execute complex workflows using advanced orchestration, memory management, and actionable intelligence. It integrates tools, interpreters, and memory systems to:
6
-
7
- - Analyze user inputs in their context.
8
- - Execute predefined workflows and dynamic actions.
9
- - Efficiently manage short-term and long-term memory.
10
- - Enable seamless integration with external APIs and tools.
1
+ # @ai.ntellect/core
11
2
 
12
3
  ---
13
4
 
14
- ## Table of Contents
15
-
16
- 1. [Architecture Components](#architecture-components)
17
- - [Agent Runtime](#agent-runtime)
18
- - [Orchestrator](#orchestrator)
19
- - [Queue Manager](#queue-manager)
20
- - [Interpreter](#interpreter)
21
- - [Memory System](#memory-system)
22
- - [Listeners](#listeners)
23
- - [Schedulers](#schedulers)
24
- 2. [Defining and Executing Actions](#defining-and-executing-actions)
25
- 3. [State Management and Recursion](#state-management-and-recursion)
26
- 4. [Installation and Configuration](#installation-and-configuration)
27
- 5. [Usage Example](#usage-example)
28
- 6. [Work in Progress (WIP)](#work-in-progress-wip)
5
+ ## Introduction
29
6
 
30
- ---
7
+ **@ai.ntellect/core** is a highly extensible, graph-based workflow framework designed to tackle complex automation scenarios, pipelines, AI-driven agent flows, and even blockchain process orchestration. By modeling your processes as **Graphs** composed of **Nodes**, you can intuitively define both sequential and parallel task execution. The framework provides robust features including:
31
8
 
32
- ## Architecture Components
9
+ - **Dynamic state management** with optional schema validation
10
+ - **Parallel and conditional branching** execution
11
+ - **Controller-based orchestration** of multiple workflows
12
+ - **Subgraph** delegation for modular design
13
+ - **Memory management** for agents and chatbots (e.g., storing user context or embeddings)
14
+ - **Integration** with real-time notifiers and persistence layers
33
15
 
34
- ### Agent Runtime
16
+ Whether you’re building a data pipeline, an AI-driven bot, or an automated blockchain process, @ai.ntellect/core offers a concise yet powerful suite of tooling to handle the complexity of stateful, event-driven orchestration.
35
17
 
36
- The `AgentRuntime` is the main engine coordinating the overall workflow. It connects all components and ensures tasks are executed efficiently.
18
+ ---
37
19
 
38
- **Responsibilities:**
20
+ ## Installation
39
21
 
40
- - Build context for the current state using memory systems (RAG and CAG).
41
- - Orchestrate actions using the queue manager.
42
- - Leverage interpreters to analyze results and generate responses.
22
+ ### Prerequisites
43
23
 
44
- #### Context Building
24
+ - **Node.js** (14.x or higher recommended)
25
+ - A package manager such as **npm** or **yarn**
45
26
 
46
- The `buildContext` method creates a complete context by:
27
+ ### Installing the package
47
28
 
48
- 1. Adding tools and user requests.
49
- 2. Retrieving recent actions via cache memory (CAG).
50
- 3. Fetching relevant knowledge from persistent memory (RAG).
51
- 4. Including available interpreters for the request.
29
+ ```bash
30
+ npm install @ai.ntellect/core
31
+ ```
52
32
 
53
- #### Workflow Processing
33
+ Or using Yarn:
54
34
 
55
- The `process` method:
35
+ ```bash
36
+ yarn add @ai.ntellect/core
37
+ ```
56
38
 
57
- 1. Generates responses based on context using a language model.
58
- 2. Handles recursive workflows for action execution.
59
- 3. Selects appropriate interpreters to analyze results.
39
+ Or using pnpm:
60
40
 
61
- ---
41
+ ```bash
42
+ pnpm add @ai.ntellect/core
43
+ ```
62
44
 
63
- ### Orchestrator
45
+ ### Initial configuration
64
46
 
65
- The **orchestrator** directs workflows by analyzing user inputs and planning actions. It interacts with tools, memory systems, and interpreters to ensure logical execution.
47
+ - **Import the necessary classes**:
66
48
 
67
- **Key Features:**
49
+ ```ts
50
+ import { GraphEngine, GraphController } from "@ai.ntellect/core";
51
+ ```
68
52
 
69
- - Dynamic action selection based on context.
70
- - Memory interaction management for RAG and CAG operations.
71
- - Multi-step workflow management with iterative refinement.
53
+ - **(Optional) Define your state schema** using a validation library like [Zod](https://zod.dev) to ensure your data remains consistent throughout workflow execution.
54
+ - **Configure** advanced features (e.g., persistence, notifications, memory services) before running your workflows.
72
55
 
73
56
  ---
74
57
 
75
- ### Queue Manager
76
-
77
- The **queue manager** is responsible for organizing and executing actions in the correct order, whether sequential or parallel. It acts as the central mechanism for managing workflows, ensuring each action is properly queued, validated, and executed.
78
-
79
- **Main Responsibilities:**
80
-
81
- 1. **Action Queueing:**
82
-
83
- - Actions are added to a queue for execution, individually or in batches.
84
- - Includes logging support for debugging and traceability.
58
+ ## Core concepts
59
+
60
+ @ai.ntellect/core revolves around the idea of **Graphs** and **Nodes**. On top of these concepts, the framework provides a powerful **Engine**, a high-level **Controller**, and optional **Memory** management for specialized use cases (like AI agents). This section explores each concept in detail.
61
+
62
+ ### Graph
63
+
64
+ A **Graph** is a directed structure describing a workflow. It consists of:
65
+
66
+ - **Nodes**: the tasks or steps in your workflow
67
+ - **Edges (relationships)**: transitions from one node to another
68
+
69
+ You define a **Graph** via a `GraphDefinition`, specifying:
70
+
71
+ 1. A unique **name** for the graph
72
+ 2. An **entryNode** (starting point)
73
+ 3. A map of **node objects** (each one describes a single node’s logic and transitions)
74
+
75
+ #### Why use graphs?
76
+
77
+ - **Clear visualization**: easily see the flow of tasks, including parallel branches.
78
+ - **Condition-based transitions**: skip or filter nodes on the fly.
79
+ - **Subgraph usage**: encapsulate common flows for reuse.
80
+
81
+ #### Example of a simple graph definition
82
+
83
+ ```ts
84
+ const myGraphDefinition = {
85
+ name: "my-simple-graph",
86
+ entryNode: "start",
87
+ nodes: {
88
+ start: {
89
+ name: "start",
90
+ execute: async (_params, state) => {
91
+ return { context: { ...state.context, status: "initialized" } };
92
+ },
93
+ relationships: [{ name: "process" }],
94
+ },
95
+ process: {
96
+ name: "process",
97
+ execute: async (_params, state) => {
98
+ // do something
99
+ return { context: { ...state.context, processed: true } };
100
+ },
101
+ relationships: [{ name: "finish" }],
102
+ },
103
+ finish: {
104
+ name: "finish",
105
+ execute: async (_params, state) => state,
106
+ relationships: [],
107
+ },
108
+ },
109
+ };
110
+ ```
85
111
 
86
- 2. **Action Processing:**
112
+ ### Node
87
113
 
88
- - Executes actions while maintaining correct order.
89
- - Respects dependencies between actions.
90
- - Handles errors or confirmations via callbacks.
114
+ A **Node** is a fundamental unit of work within a graph. Each node defines:
91
115
 
92
- 3. **Confirmation Management:**
93
- - Supports prompts for critical actions.
94
- - Relies on callbacks to decide whether to proceed with specific actions.
116
+ - **name**: a unique identifier within the graph
117
+ - **execute**: the asynchronous function that implements the node’s logic
118
+ - **condition** (optional): a function returning a boolean determining if this node should run
119
+ - **relationships**: an array of transitions to subsequent nodes
120
+ - **events** (optional): an array of event names that can trigger the node (bypassing usual transitions)
95
121
 
96
- **Example:**
122
+ #### Listening to events
97
123
 
98
- ```typescript
99
- import { ActionQueueManager } from "@ai-ntellect/core";
100
- import { actions, callbacks } from "@ai-ntellect/core/examples";
124
+ Besides sequential or parallel execution, a node can listen to custom events:
101
125
 
102
- const queueManager = new ActionQueueManager(actions, callbacks);
103
- queueManager.addToQueue([{ name: "fetch-data", parameters: [...] }]);
104
- const results = await queueManager.processQueue();
105
- console.log("Results:", results);
126
+ ```ts
127
+ {
128
+ name: "eventDrivenNode",
129
+ events: ["USER_CREATED"],
130
+ execute: async (params, state) => {
131
+ console.log("User created:", params);
132
+ return state;
133
+ },
134
+ }
106
135
  ```
107
136
 
108
- ---
137
+ If the **Engine** later calls `engine.emit("USER_CREATED", {...})`, this node will be triggered. This mechanism is extremely powerful for event-driven architectures (e.g., a chatbot responding to user events, or a blockchain node responding to on-chain events).
109
138
 
110
- ### Interpreter
139
+ ### GraphEngine
111
140
 
112
- The **interpreter** specializes in analyzing results and generating domain-specific insights. Each interpreter is tailored for a specific use case and uses its own character configuration.
141
+ #### Overview
113
142
 
114
- **Examples:**
143
+ The **GraphEngine** (often shortened to “engine”) is responsible for:
115
144
 
116
- 1. **MarketInterpreter**: Analyzes financial market data.
117
- 2. **SecurityInterpreter**: Performs security checks.
118
- 3. **GeneralInterpreter**: Processes general-purpose requests.
145
+ - Loading a `GraphDefinition`
146
+ - Executing its nodes according to **relationships** and optional **conditions**
147
+ - Handling **state** updates after each node execution
148
+ - Managing **event** emissions and listening for event-driven nodes
149
+ - Allowing **parallel** or **sequential** node execution
150
+ - Managing **subgraphs** if your workflow references external graph definitions
119
151
 
120
- #### Interpretation Workflow
152
+ ```ts
153
+ import { GraphEngine } from "ai.ntellect/core";
121
154
 
122
- 1. Builds context with the current state, including results and user requests.
123
- 2. Uses the language model to generate actionable insights.
124
- 3. Provides detailed responses for the end user.
155
+ const engine = new GraphEngine(myGraphDefinition);
156
+ await engine.execute({ context: { user: "Alice" } }, "start");
157
+ ```
125
158
 
126
- ---
159
+ ### GraphController
127
160
 
128
- ### Memory System
161
+ #### Overview
129
162
 
130
- The memory architecture combines short-term and long-term memory to provide contextual processing.
163
+ The **GraphController** provides a **high-level orchestration** mechanism for multiple graphs. Instead of running a single workflow, you can define **actions**—each tied to a particular workflow—and the controller executes them in sequence (or other patterns) based on your configuration.
131
164
 
132
- #### Memory Types
165
+ ```ts
166
+ import { GraphController } from "ai.ntellect/core";
133
167
 
134
- 1. **Cache Memory (Redis):**
135
- - Stores temporary data for quick access.
136
- - Examples: Recent actions, session data.
137
- 2. **Persistent Memory (Meilisearch):**
138
- - Stores long-term data such as historical interactions and knowledge.
139
- - Supports semantic searches and vector-based retrievals.
168
+ const controller = new GraphController<any>();
169
+ const resultState = await controller.run(
170
+ [
171
+ {
172
+ name: "my-simple-graph",
173
+ parameters: [
174
+ { name: "user", value: "Alice" },
175
+ { name: "count", value: 10 },
176
+ ],
177
+ },
178
+ ],
179
+ [myGraphDefinition, someOtherGraphDef]
180
+ );
140
181
 
141
- ---
182
+ console.log(resultState);
183
+ // => final state after running 'my-simple-graph'
184
+ ```
142
185
 
143
- ### Listeners
186
+ **Use cases**:
144
187
 
145
- **Listeners** connect to external events via WebSocket. They listen for real-time updates and trigger specific actions or callbacks in response to events.
188
+ - **Batch execution** of multiple workflows
189
+ - **Multi-tenant** orchestration where each tenant’s configuration is an “action”
190
+ - **Chained flows**: run workflow A, then run workflow B with the result of A
146
191
 
147
- **Key Features:**
192
+ ### Memory management
148
193
 
149
- - Connect to WebSockets to listen for events.
150
- - Manage subscriptions with custom messages.
151
- - Trigger callbacks to process received data.
194
+ In advanced workflows, especially with chatbots or AI agents, you might want to maintain a **memory** of previous interactions or references. @ai.ntellect/core accommodates this via an abstract class **BaseMemory** and a dedicated **BaseMemoryService** for storing and retrieving data. This can be used to store embeddings, historical context, or any ephemeral data needed for your workflows.
152
195
 
153
- **Usage Example:**
196
+ ```ts
197
+ import { BaseMemory } from "ai.ntellect/core";
154
198
 
155
- ```typescript
156
- agent.addListener(
157
- "listener-id",
158
- "wss://example.com/socket",
159
- () => JSON.stringify({ action: "subscribe" }),
160
- async (data) => {
161
- console.log("Received data:", data);
199
+ // Example concrete class
200
+ class MyMemory extends BaseMemory {
201
+ async init(): Promise<void> {
202
+ /*...*/
162
203
  }
163
- );
204
+ async createMemory(input): Promise<BaseMemoryType | undefined> {
205
+ /*...*/
206
+ }
207
+ async getMemoryById(id, roomId): Promise<BaseMemoryType | null> {
208
+ /*...*/
209
+ }
210
+ // ... other methods
211
+ }
164
212
  ```
165
213
 
166
- ---
214
+ **Possible storage backends**:
167
215
 
168
- ### Schedulers
216
+ - In-memory
217
+ - Redis / Key-value stores
218
+ - SQL / NoSQL databases
169
219
 
170
- **Schedulers** allow tasks or actions to be scheduled for later execution. They use cron expressions to define scheduling intervals.
220
+ **Key benefits**:
171
221
 
172
- **Key Features:**
222
+ - Store query embeddings for AI-based search
223
+ - Maintain user session context (e.g., conversation flows)
224
+ - Rapidly retrieve and update relevant data at runtime
173
225
 
174
- - Cron-based scheduling.
175
- - Support for recurring and non-recurring tasks.
176
- - Management and cancellation of scheduled tasks.
177
-
178
- **Usage Example:**
226
+ ---
179
227
 
180
- ```typescript
181
- const scheduler = new TaskScheduler(agentRuntime, redisCache);
228
+ ## Advanced usage and features
182
229
 
183
- const taskId = await scheduler.scheduleRequest({
184
- originalRequest: "Market analysis",
185
- cronExpression: "0 9 * * *", // Every day at 9 AM
186
- });
230
+ ### Subgraphs for modularity
187
231
 
188
- console.log(`Task scheduled with ID: ${taskId}`);
232
+ Nodes can delegate execution to a **subgraph**, enabling large workflows to be broken into reusable components:
189
233
 
190
- // Cancel the task if needed
191
- scheduler.cancelScheduledRequest(taskId);
234
+ ```ts
235
+ const subGraphEngine = new GraphEngine(subGraphDef);
236
+ mainGraphEngine.addSubGraph(subGraphEngine, "sub-start", "sub-workflow");
192
237
  ```
193
238
 
194
- ---
239
+ **Why subgraphs**:
195
240
 
196
- ## Defining and Executing Actions
241
+ - **Reusability**: common routines can be maintained independently
242
+ - **Maintainability**: isolate large logic in smaller workflows
197
243
 
198
- ### What is an Action?
244
+ ### Parallel execution
199
245
 
200
- Actions are the fundamental tasks executed by the framework. Each action includes:
246
+ The `executeParallel` method allows you to simultaneously run multiple nodes that don’t have direct dependencies on each other. You can limit concurrency to prevent overwhelming external resources:
201
247
 
202
- - A unique name and description.
203
- - Input parameters validated using schemas.
204
- - Execution logic encapsulated in the `execute` method.
248
+ ```ts
249
+ await engine.executeParallel(
250
+ { context: { userId: 42 } },
251
+ ["nodeA", "nodeB", "nodeC"],
252
+ 2 // concurrency limit
253
+ );
254
+ ```
205
255
 
206
- ### Action Example
256
+ ### Real-time notifications and events
207
257
 
208
- ```typescript
209
- import { z } from "zod";
210
- import { parseEther } from "ethers";
258
+ By attaching a **RealTimeNotifier**, each node’s start, completion, or error can be broadcast to external systems (WebSocket, Slack, logging, etc.):
211
259
 
212
- export const prepareTransaction = {
213
- name: "prepare-transaction",
214
- description: "Prepares a token transfer for user approval.",
215
- parameters: z.object({
216
- walletAddress: z.string(),
217
- amount: z.string(),
218
- networkId: z.string(),
219
- }),
220
- execute: async ({ walletAddress, amount, networkId }) => {
221
- return {
222
- to: walletAddress,
223
- value: parseEther(amount).toString(),
224
- network: networkId,
225
- };
260
+ ```ts
261
+ const notifier = {
262
+ notify: (event, data) => {
263
+ console.log(`[NOTIFY] ${event}`, data);
226
264
  },
227
265
  };
266
+ engine.setNotifier(notifier);
228
267
  ```
229
268
 
230
- ---
231
-
232
- ## State Management and Recursion
233
-
234
- The agent manages state and recursive workflows to ensure actions are executed in an orderly manner and to completion, while adhering to a maximum number of iterations to avoid infinite loops.
235
-
236
- ### State Management
237
-
238
- The state (`State`) includes:
239
-
240
- - `currentContext`: The current context of the user request.
241
- - `previousActions`: A list of previously executed actions.
242
-
243
- When an action is completed, the state is updated to include:
244
-
245
- - Results from previous actions.
246
- - Remaining context to be processed.
247
-
248
- ### Controlled Recursion
249
-
250
- To prevent infinite loops, the system limits the number of iterations via the `maxIterations` configuration.
251
-
252
- **Workflow:**
269
+ ### Persistence and error recovery
253
270
 
254
- 1. **Initialization:** At each iteration, the agent:
271
+ For long-running or mission-critical workflows, implement a **Persistence** interface:
255
272
 
256
- - Executes actions in the queue.
257
- - Updates the state with new results.
258
-
259
- 2. **Limit Validation:**
260
-
261
- - If the number of iterations exceeds `maxIterations`, processing is stopped with a "Max iterations reached" message.
262
-
263
- 3. **Recursion:**
264
- - If actions remain to be executed, the agent recursively calls the `process` method with the updated state.
265
-
266
- **State and Recursion Example:**
267
-
268
- ```typescript
269
- const updatedNextState: State = {
270
- ...state,
271
- currentContext: state.currentContext,
272
- previousActions: [...(state.previousActions || []), ...(results || [])],
273
+ ```ts
274
+ const myPersistence = {
275
+ saveState: async (graphName, state, currentNode) => {
276
+ /* store in DB */
277
+ },
278
+ loadState: async () => {
279
+ /* retrieve from DB */ return null;
280
+ },
273
281
  };
274
-
275
- if (countIterations < this.config.maxIterations) {
276
- return this.process(updatedNextState);
277
- } else {
278
- console.log("Max iterations reached");
279
- response.shouldContinue = false;
280
- }
282
+ engine.setPersistence(myPersistence);
281
283
  ```
282
284
 
283
- ---
284
-
285
- ## Installation and Configuration
285
+ If a workflow fails, you can reload from the last checkpoint and resume execution.
286
286
 
287
- ### Install Dependencies
287
+ ---
288
288
 
289
- ```bash
290
- npm install
289
+ ## Example: agent workflow with memory
290
+
291
+ Below is an example `createMainGraph` definition demonstrating how you can structure an AI or chatbot-like agent using a controller node, agenda scheduling, interpretation, and memory storage. This pattern is useful in:
292
+
293
+ - **Chatbots** handling complex dialogues
294
+ - **AI reasoning systems** that need to store partial results
295
+ - **Planning agents** that schedule tasks or actions asynchronously
296
+
297
+ ```ts
298
+ import { GraphDefinition } from "@/types";
299
+ // Assume Agent, MyContext, isNotStopped, shouldRetry, etc. are defined
300
+
301
+ export const createMainGraph = (
302
+ agent: Agent,
303
+ prompt: string,
304
+ callbacks?: any
305
+ ): GraphDefinition<MyContext> => ({
306
+ name: "agent",
307
+ entryNode: "orchestrator",
308
+ nodes: {
309
+ orchestrator: {
310
+ name: "orchestrator",
311
+ description: "Make a decision following the current context",
312
+ execute: async () => {
313
+ /* your orchestrator logic */
314
+ },
315
+ condition: (state) => isNotStopped(state) || shouldRetry(state),
316
+ relationships: [
317
+ { name: "controller", description: "Execute multiple workflows" },
318
+ { name: "agenda", description: "Schedule actions for the future" },
319
+ {
320
+ name: "interpreter",
321
+ description: "Interpret the results of actions",
322
+ },
323
+ ],
324
+ },
325
+ controller: {
326
+ name: "controller",
327
+ description: "Execute multiple workflows if available",
328
+ execute: async () => {
329
+ /* handle or queue workflow actions */
330
+ },
331
+ condition: () => {
332
+ const currentState = agent.graph.getState();
333
+ return hasActions(currentState) && isNotStopped(currentState);
334
+ },
335
+ relationships: [{ name: "orchestrator" }],
336
+ },
337
+ agenda: {
338
+ name: "agenda",
339
+ description: "Schedule actions for the future",
340
+ execute: async () => {
341
+ /* handle scheduling logic */
342
+ },
343
+ condition: hasActions,
344
+ },
345
+ interpreter: {
346
+ name: "interpreter",
347
+ description: "Interpret the results of the actions",
348
+ execute: async () => {
349
+ /* interpret results, maybe using memory */
350
+ },
351
+ condition: () => {
352
+ const currentState = agent.graph.getState();
353
+ return (
354
+ isInterpreterDefined(currentState) &&
355
+ isResultsDefined(currentState) &&
356
+ isStopped(currentState)
357
+ );
358
+ },
359
+ relationships: [{ name: "memory", description: "Save memory" }],
360
+ },
361
+ memory: {
362
+ name: "memory",
363
+ description: "Save memory",
364
+ execute: async () => {
365
+ /* store or retrieve conversation states */
366
+ },
367
+ condition: () => {
368
+ const currentState = agent.graph.getState();
369
+ return isResultsDefined(currentState);
370
+ },
371
+ },
372
+ },
373
+ });
291
374
  ```
292
375
 
293
- ### Configure External Services
376
+ This structure highlights how an **Agent** can leverage the **GraphEngine** for decision-making, scheduling tasks, interpreting outcomes, and ultimately storing relevant data in memory before concluding.
294
377
 
295
- #### Redis (Cache Memory)
296
-
297
- ```bash
298
- docker run --name redis -d -p 6379:6379 redis
299
- ```
378
+ ---
300
379
 
301
- #### Meilisearch (Persistent Memory)
380
+ ## Real-world use cases
302
381
 
303
- ```bash
304
- curl -L https://install.meilisearch.com | sh
305
- ./meilisearch --master-key="YOUR_MASTER_KEY"
306
- ```
382
+ 1. **Automation**: Orchestrate tasks like file processing, data validation, and uploading in a single graph.
383
+ 2. **Data pipeline**: Stream logs into a transformation flow with parallel processing and conditional branches.
384
+ 3. **AI bots**: Manage conversation state, memory, and advanced decision trees for chat-based agents.
385
+ 4. **Blockchain**: Sequence complex contract interactions, handle parallel on-chain calls, and revert safely on errors.
386
+ 5. **Task scheduling**: Combine GraphController with multiple workflows to handle enterprise-wide daily or weekly tasks.
307
387
 
308
388
  ---
309
389
 
310
- ## Usage Example
311
-
312
- ### Initialize the Agent
313
-
314
- ```typescript
315
- import { deepseek } from "@ai-ntellect/core";
316
- import { Agent } from "@ai-ntellect/core";
317
- import { checkHoneypot, fetchMarkPrice } from "@ai-ntellect/core/actions";
318
- import {
319
- generalInterpreterCharacter,
320
- marketInterpreterCharacter,
321
- securityInterpreterCharacter,
322
- } from "@ai-ntellect/core/interpreter/context";
390
+ ## Conclusion
323
391
 
324
- const model = deepseek("deepseek-reasoner");
392
+ @ai.ntellect/core offers a **comprehensive**, **modular**, and **event-driven** environment to model, execute, and extend workflows of any complexity. By leveraging **Graphs** and **Nodes** alongside robust tooling such as **GraphEngine**, **GraphController**, and **Memory** services, you can adapt the framework to fit an array of domains, from classic data pipelines to cutting-edge AI agent systems.
325
393
 
326
- const agent = new Agent({
327
- orchestrator: {
328
- model,
329
- tools: [checkHoneypot, fetchMarkPrice],
330
- },
331
- interpreters: [
332
- new Interpreter({
333
- name: "security",
334
- model,
335
- character: securityInterpreterCharacter,
336
- }),
337
- new Interpreter({
338
- name: "market",
339
- model,
340
- character: marketInterpreterCharacter,
341
- }),
342
- new Interpreter({
343
- name: "general",
344
- model,
345
- character: generalInterpreterCharacter,
346
- }),
347
- ],
348
- memoryManager: {
349
- model,
350
- },
351
- maxIterations: 3,
352
- });
353
- ```
394
+ ### Key points to remember
354
395
 
355
- ### Process a Request
396
+ - **Graphs** define the structure of your workflow; **Nodes** encapsulate the logic.
397
+ - **GraphEngine** executes a single graph, handling state, conditions, and events.
398
+ - **GraphController** orchestrates multiple graphs in a higher-level scope.
399
+ - **Memory** management supports advanced agent use cases, storing embeddings or conversation history.
400
+ - **Parallel execution**, **subgraphs**, **real-time notifications**, and **persistence** provide powerful abstractions to scale with your needs.
356
401
 
357
- ```typescript
358
- const state = {
359
- currentContext: "Analyze XRP/USD market trends",
360
- previousActions: [],
361
- };
402
+ For more in-depth guides, examples, or to contribute, visit our repository or consult the extended documentation. If you need specialized solutions—like a custom memory store or a unique scheduling system—**@ai.ntellect/core**’s open architecture makes it straightforward to extend or integrate with your existing stack.
362
403
 
363
- const result = await agent.process(state);
364
- console.log("Result:", result);
365
- ```
404
+ Use it for automation, AI bots, blockchain interactions, or any stateful workflow that demands reliability, flexibility, and clarity.