@ai.ntellect/core 0.4.0 → 0.5.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.
- package/README.FR.md +624 -18
- package/README.md +127 -72
- package/agent/index.ts +57 -149
- package/agent/workflow/conditions.ts +16 -0
- package/agent/workflow/handlers/interpreter.handler.ts +48 -0
- package/agent/workflow/handlers/memory.handler.ts +106 -0
- package/agent/workflow/handlers/orchestrator.handler.ts +23 -0
- package/agent/workflow/handlers/queue.handler.ts +34 -0
- package/agent/workflow/handlers/scheduler.handler.ts +61 -0
- package/agent/workflow/index.ts +62 -0
- package/dist/agent/index.d.ts +1 -1
- package/dist/agent/index.js +3 -3
- package/{agent/tools → examples/actions}/get-rss.ts +8 -1
- package/examples/index.ts +10 -15
- package/index.html +42 -0
- package/llm/dynamic-condition/example.ts +36 -0
- package/llm/dynamic-condition/index.ts +108 -0
- package/llm/interpreter/context.ts +5 -12
- package/llm/interpreter/index.ts +20 -16
- package/llm/memory-manager/context.ts +4 -6
- package/llm/memory-manager/index.ts +32 -80
- package/llm/orchestrator/context.ts +5 -8
- package/llm/orchestrator/index.ts +62 -102
- package/llm/orchestrator/types.ts +2 -2
- package/package.json +3 -1
- package/script.js +167 -0
- package/services/{scheduler.ts → agenda.ts} +20 -35
- package/services/cache.ts +298 -0
- package/services/queue.ts +3 -3
- package/services/workflow.ts +491 -0
- package/t.ts +21 -129
- package/tsconfig.json +2 -1
- package/types.ts +91 -12
- package/utils/generate-object.ts +24 -12
- package/utils/inject-actions.ts +3 -3
- package/utils/state-manager.ts +25 -0
- package/bull.ts +0 -5
- package/services/redis-cache.ts +0 -128
- package/t.spec +0 -38
package/README.md
CHANGED
@@ -4,57 +4,59 @@
|
|
4
4
|
|
5
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
6
|
|
7
|
-
-
|
7
|
+
- Analyze user inputs in their context.
|
8
8
|
- Execute predefined workflows and dynamic actions.
|
9
9
|
- Efficiently manage short-term and long-term memory.
|
10
|
-
-
|
10
|
+
- Enable seamless integration with external APIs and tools.
|
11
11
|
|
12
12
|
---
|
13
13
|
|
14
|
-
## Table of
|
14
|
+
## Table of Contents
|
15
15
|
|
16
|
-
1. [Architecture
|
17
|
-
- [Agent
|
16
|
+
1. [Architecture Components](#architecture-components)
|
17
|
+
- [Agent Runtime](#agent-runtime)
|
18
18
|
- [Orchestrator](#orchestrator)
|
19
|
-
- [Queue
|
19
|
+
- [Queue Manager](#queue-manager)
|
20
20
|
- [Interpreter](#interpreter)
|
21
|
-
- [Memory
|
22
|
-
|
23
|
-
|
24
|
-
|
25
|
-
|
26
|
-
|
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)
|
27
29
|
|
28
30
|
---
|
29
31
|
|
30
|
-
## Architecture
|
32
|
+
## Architecture Components
|
31
33
|
|
32
|
-
### Agent
|
34
|
+
### Agent Runtime
|
33
35
|
|
34
|
-
The `AgentRuntime` is the
|
36
|
+
The `AgentRuntime` is the main engine coordinating the overall workflow. It connects all components and ensures tasks are executed efficiently.
|
35
37
|
|
36
38
|
**Responsibilities:**
|
37
39
|
|
38
40
|
- Build context for the current state using memory systems (RAG and CAG).
|
39
|
-
- Orchestrate actions using the
|
41
|
+
- Orchestrate actions using the queue manager.
|
40
42
|
- Leverage interpreters to analyze results and generate responses.
|
41
43
|
|
42
|
-
#### Context
|
44
|
+
#### Context Building
|
43
45
|
|
44
|
-
The `buildContext` method
|
46
|
+
The `buildContext` method creates a complete context by:
|
45
47
|
|
46
48
|
1. Adding tools and user requests.
|
47
|
-
2. Retrieving recent actions
|
49
|
+
2. Retrieving recent actions via cache memory (CAG).
|
48
50
|
3. Fetching relevant knowledge from persistent memory (RAG).
|
49
51
|
4. Including available interpreters for the request.
|
50
52
|
|
51
|
-
#### Processing
|
53
|
+
#### Workflow Processing
|
52
54
|
|
53
55
|
The `process` method:
|
54
56
|
|
55
|
-
1. Generates responses based on
|
57
|
+
1. Generates responses based on context using a language model.
|
56
58
|
2. Handles recursive workflows for action execution.
|
57
|
-
3. Selects appropriate interpreters
|
59
|
+
3. Selects appropriate interpreters to analyze results.
|
58
60
|
|
59
61
|
---
|
60
62
|
|
@@ -62,33 +64,33 @@ The `process` method:
|
|
62
64
|
|
63
65
|
The **orchestrator** directs workflows by analyzing user inputs and planning actions. It interacts with tools, memory systems, and interpreters to ensure logical execution.
|
64
66
|
|
65
|
-
**Key
|
67
|
+
**Key Features:**
|
66
68
|
|
67
|
-
- Dynamic selection
|
68
|
-
-
|
69
|
-
- Multi-step workflow
|
69
|
+
- Dynamic action selection based on context.
|
70
|
+
- Memory interaction management for RAG and CAG operations.
|
71
|
+
- Multi-step workflow management with iterative refinement.
|
70
72
|
|
71
73
|
---
|
72
74
|
|
73
|
-
### Queue
|
75
|
+
### Queue Manager
|
74
76
|
|
75
|
-
The **queue manager**
|
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.
|
76
78
|
|
77
|
-
**Responsibilities:**
|
79
|
+
**Main Responsibilities:**
|
78
80
|
|
79
|
-
1. **Queueing
|
81
|
+
1. **Action Queueing:**
|
80
82
|
|
81
|
-
- Actions are added to a queue for execution,
|
82
|
-
-
|
83
|
+
- Actions are added to a queue for execution, individually or in batches.
|
84
|
+
- Includes logging support for debugging and traceability.
|
83
85
|
|
84
|
-
2. **Processing
|
86
|
+
2. **Action Processing:**
|
85
87
|
|
86
|
-
- Executes actions
|
87
|
-
-
|
88
|
+
- Executes actions while maintaining correct order.
|
89
|
+
- Respects dependencies between actions.
|
88
90
|
- Handles errors or confirmations via callbacks.
|
89
91
|
|
90
|
-
3. **Confirmation
|
91
|
-
- Supports
|
92
|
+
3. **Confirmation Management:**
|
93
|
+
- Supports prompts for critical actions.
|
92
94
|
- Relies on callbacks to decide whether to proceed with specific actions.
|
93
95
|
|
94
96
|
**Example:**
|
@@ -107,48 +109,101 @@ console.log("Results:", results);
|
|
107
109
|
|
108
110
|
### Interpreter
|
109
111
|
|
110
|
-
The **interpreter** specializes in analyzing results and generating domain-specific insights. Each interpreter is tailored
|
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.
|
111
113
|
|
112
114
|
**Examples:**
|
113
115
|
|
114
116
|
1. **MarketInterpreter**: Analyzes financial market data.
|
115
|
-
2. **SecurityInterpreter**:
|
117
|
+
2. **SecurityInterpreter**: Performs security checks.
|
116
118
|
3. **GeneralInterpreter**: Processes general-purpose requests.
|
117
119
|
|
118
|
-
#### Interpretation
|
120
|
+
#### Interpretation Workflow
|
119
121
|
|
120
122
|
1. Builds context with the current state, including results and user requests.
|
121
123
|
2. Uses the language model to generate actionable insights.
|
122
|
-
3. Provides detailed responses for the
|
124
|
+
3. Provides detailed responses for the end user.
|
123
125
|
|
124
126
|
---
|
125
127
|
|
126
|
-
### Memory
|
128
|
+
### Memory System
|
127
129
|
|
128
130
|
The memory architecture combines short-term and long-term memory to provide contextual processing.
|
129
131
|
|
130
|
-
#### Types
|
132
|
+
#### Memory Types
|
131
133
|
|
132
|
-
1. **Cache
|
133
|
-
- Stores temporary data for
|
134
|
+
1. **Cache Memory (Redis):**
|
135
|
+
- Stores temporary data for quick access.
|
134
136
|
- Examples: Recent actions, session data.
|
135
|
-
2. **Persistent
|
137
|
+
2. **Persistent Memory (Meilisearch):**
|
136
138
|
- Stores long-term data such as historical interactions and knowledge.
|
137
|
-
-
|
139
|
+
- Supports semantic searches and vector-based retrievals.
|
140
|
+
|
141
|
+
---
|
142
|
+
|
143
|
+
### Listeners
|
144
|
+
|
145
|
+
**Listeners** connect to external events via WebSocket. They listen for real-time updates and trigger specific actions or callbacks in response to events.
|
146
|
+
|
147
|
+
**Key Features:**
|
148
|
+
|
149
|
+
- Connect to WebSockets to listen for events.
|
150
|
+
- Manage subscriptions with custom messages.
|
151
|
+
- Trigger callbacks to process received data.
|
152
|
+
|
153
|
+
**Usage Example:**
|
154
|
+
|
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);
|
162
|
+
}
|
163
|
+
);
|
164
|
+
```
|
165
|
+
|
166
|
+
---
|
167
|
+
|
168
|
+
### Schedulers
|
169
|
+
|
170
|
+
**Schedulers** allow tasks or actions to be scheduled for later execution. They use cron expressions to define scheduling intervals.
|
171
|
+
|
172
|
+
**Key Features:**
|
173
|
+
|
174
|
+
- Cron-based scheduling.
|
175
|
+
- Support for recurring and non-recurring tasks.
|
176
|
+
- Management and cancellation of scheduled tasks.
|
177
|
+
|
178
|
+
**Usage Example:**
|
179
|
+
|
180
|
+
```typescript
|
181
|
+
const scheduler = new TaskScheduler(agentRuntime, redisCache);
|
182
|
+
|
183
|
+
const taskId = await scheduler.scheduleRequest({
|
184
|
+
originalRequest: "Market analysis",
|
185
|
+
cronExpression: "0 9 * * *", // Every day at 9 AM
|
186
|
+
});
|
187
|
+
|
188
|
+
console.log(`Task scheduled with ID: ${taskId}`);
|
189
|
+
|
190
|
+
// Cancel the task if needed
|
191
|
+
scheduler.cancelScheduledRequest(taskId);
|
192
|
+
```
|
138
193
|
|
139
194
|
---
|
140
195
|
|
141
|
-
## Defining and
|
196
|
+
## Defining and Executing Actions
|
142
197
|
|
143
|
-
### What
|
198
|
+
### What is an Action?
|
144
199
|
|
145
|
-
Actions are fundamental tasks executed by the framework. Each action includes:
|
200
|
+
Actions are the fundamental tasks executed by the framework. Each action includes:
|
146
201
|
|
147
202
|
- A unique name and description.
|
148
203
|
- Input parameters validated using schemas.
|
149
204
|
- Execution logic encapsulated in the `execute` method.
|
150
205
|
|
151
|
-
### Example
|
206
|
+
### Action Example
|
152
207
|
|
153
208
|
```typescript
|
154
209
|
import { z } from "zod";
|
@@ -156,7 +211,7 @@ import { parseEther } from "ethers";
|
|
156
211
|
|
157
212
|
export const prepareTransaction = {
|
158
213
|
name: "prepare-transaction",
|
159
|
-
description: "
|
214
|
+
description: "Prepares a token transfer for user approval.",
|
160
215
|
parameters: z.object({
|
161
216
|
walletAddress: z.string(),
|
162
217
|
amount: z.string(),
|
@@ -174,25 +229,25 @@ export const prepareTransaction = {
|
|
174
229
|
|
175
230
|
---
|
176
231
|
|
177
|
-
## State
|
232
|
+
## State Management and Recursion
|
178
233
|
|
179
|
-
The agent manages state and recursive workflows to ensure actions are executed in an orderly manner
|
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.
|
180
235
|
|
181
|
-
### State
|
236
|
+
### State Management
|
182
237
|
|
183
238
|
The state (`State`) includes:
|
184
239
|
|
185
|
-
- `currentContext`:
|
186
|
-
- `previousActions`:
|
240
|
+
- `currentContext`: The current context of the user request.
|
241
|
+
- `previousActions`: A list of previously executed actions.
|
187
242
|
|
188
243
|
When an action is completed, the state is updated to include:
|
189
244
|
|
190
|
-
- Results
|
191
|
-
- Remaining context to
|
245
|
+
- Results from previous actions.
|
246
|
+
- Remaining context to be processed.
|
192
247
|
|
193
|
-
### Controlled
|
248
|
+
### Controlled Recursion
|
194
249
|
|
195
|
-
To prevent infinite loops, the system limits the number of iterations
|
250
|
+
To prevent infinite loops, the system limits the number of iterations via the `maxIterations` configuration.
|
196
251
|
|
197
252
|
**Workflow:**
|
198
253
|
|
@@ -201,14 +256,14 @@ To prevent infinite loops, the system limits the number of iterations using the
|
|
201
256
|
- Executes actions in the queue.
|
202
257
|
- Updates the state with new results.
|
203
258
|
|
204
|
-
2. **Limit
|
259
|
+
2. **Limit Validation:**
|
205
260
|
|
206
|
-
- If the
|
261
|
+
- If the number of iterations exceeds `maxIterations`, processing is stopped with a "Max iterations reached" message.
|
207
262
|
|
208
263
|
3. **Recursion:**
|
209
264
|
- If actions remain to be executed, the agent recursively calls the `process` method with the updated state.
|
210
265
|
|
211
|
-
**Example:**
|
266
|
+
**State and Recursion Example:**
|
212
267
|
|
213
268
|
```typescript
|
214
269
|
const updatedNextState: State = {
|
@@ -227,23 +282,23 @@ if (countIterations < this.config.maxIterations) {
|
|
227
282
|
|
228
283
|
---
|
229
284
|
|
230
|
-
## Installation and
|
285
|
+
## Installation and Configuration
|
231
286
|
|
232
|
-
### Install
|
287
|
+
### Install Dependencies
|
233
288
|
|
234
289
|
```bash
|
235
290
|
npm install
|
236
291
|
```
|
237
292
|
|
238
|
-
### Configure
|
293
|
+
### Configure External Services
|
239
294
|
|
240
|
-
#### Redis (
|
295
|
+
#### Redis (Cache Memory)
|
241
296
|
|
242
297
|
```bash
|
243
298
|
docker run --name redis -d -p 6379:6379 redis
|
244
299
|
```
|
245
300
|
|
246
|
-
#### Meilisearch (
|
301
|
+
#### Meilisearch (Persistent Memory)
|
247
302
|
|
248
303
|
```bash
|
249
304
|
curl -L https://install.meilisearch.com | sh
|
@@ -252,9 +307,9 @@ curl -L https://install.meilisearch.com | sh
|
|
252
307
|
|
253
308
|
---
|
254
309
|
|
255
|
-
## Example
|
310
|
+
## Usage Example
|
256
311
|
|
257
|
-
### Initialize the
|
312
|
+
### Initialize the Agent
|
258
313
|
|
259
314
|
```typescript
|
260
315
|
import { deepseek } from "@ai-ntellect/core";
|
@@ -297,7 +352,7 @@ const agent = new Agent({
|
|
297
352
|
});
|
298
353
|
```
|
299
354
|
|
300
|
-
### Process a
|
355
|
+
### Process a Request
|
301
356
|
|
302
357
|
```typescript
|
303
358
|
const state = {
|
package/agent/index.ts
CHANGED
@@ -2,33 +2,25 @@ import { LanguageModel } from "ai";
|
|
2
2
|
import WebSocket from "ws";
|
3
3
|
import { Interpreter } from "../llm/interpreter";
|
4
4
|
import { MemoryManager } from "../llm/memory-manager";
|
5
|
-
import {
|
6
|
-
import { State } from "../llm/orchestrator/types";
|
5
|
+
import { Orchestrator } from "../llm/orchestrator";
|
7
6
|
import { CacheMemory } from "../memory/cache";
|
8
7
|
import { PersistentMemory } from "../memory/persistent";
|
9
|
-
import {
|
10
|
-
import {
|
11
|
-
import {
|
12
|
-
import {
|
13
|
-
export class Agent {
|
14
|
-
private readonly agent: AgentRuntime;
|
15
|
-
private readonly memoryManager: MemoryManager;
|
16
|
-
private readonly cache: RedisCache;
|
8
|
+
import { CacheConfig, RedisCache } from "../services/cache";
|
9
|
+
import { Workflow } from "../services/workflow";
|
10
|
+
import { AgentEvent, MyContext, QueueCallbacks, SharedState } from "../types";
|
11
|
+
import { createMainWorkflow } from "./workflow";
|
17
12
|
|
18
|
-
|
13
|
+
export class Agent {
|
14
|
+
public readonly memoryManager: MemoryManager;
|
15
|
+
public readonly cache: RedisCache;
|
16
|
+
public readonly orchestrator: Orchestrator;
|
17
|
+
private listeners: Map<
|
19
18
|
string,
|
20
19
|
{ socket: WebSocket; callback: (data: any) => Promise<void> }
|
21
20
|
> = new Map();
|
22
|
-
|
23
|
-
orchestrator: {
|
24
|
-
model: LanguageModel;
|
25
|
-
tools: ActionSchema[];
|
26
|
-
memory?: {
|
27
|
-
cache?: CacheMemory;
|
28
|
-
persistent?: PersistentMemory;
|
29
|
-
};
|
30
|
-
};
|
21
|
+
public readonly config: {
|
31
22
|
interpreters: Interpreter[];
|
23
|
+
orchestrator: Orchestrator;
|
32
24
|
memoryManager: {
|
33
25
|
model: LanguageModel;
|
34
26
|
memory?: {
|
@@ -41,15 +33,8 @@ export class Agent {
|
|
41
33
|
|
42
34
|
constructor(config: {
|
43
35
|
cache: CacheConfig;
|
44
|
-
orchestrator: {
|
45
|
-
model: LanguageModel;
|
46
|
-
tools: ActionSchema[];
|
47
|
-
memory?: {
|
48
|
-
cache?: CacheMemory;
|
49
|
-
persistent?: PersistentMemory;
|
50
|
-
};
|
51
|
-
};
|
52
36
|
interpreters: Interpreter[];
|
37
|
+
orchestrator: Orchestrator;
|
53
38
|
memoryManager: {
|
54
39
|
model: LanguageModel;
|
55
40
|
memory?: {
|
@@ -62,13 +47,7 @@ export class Agent {
|
|
62
47
|
}) {
|
63
48
|
this.cache = new RedisCache(config.cache);
|
64
49
|
this.config = config;
|
65
|
-
|
66
|
-
config.orchestrator.model,
|
67
|
-
config.orchestrator.tools,
|
68
|
-
config.interpreters,
|
69
|
-
config.cache,
|
70
|
-
config.orchestrator.memory
|
71
|
-
);
|
50
|
+
|
72
51
|
this.memoryManager = new MemoryManager({
|
73
52
|
model: config.memoryManager.model,
|
74
53
|
memory: {
|
@@ -76,142 +55,71 @@ export class Agent {
|
|
76
55
|
persistent: config.memoryManager.memory?.persistent ?? undefined,
|
77
56
|
},
|
78
57
|
});
|
58
|
+
this.orchestrator = config.orchestrator;
|
79
59
|
this.config.maxIterations = 3;
|
80
60
|
}
|
81
61
|
|
82
|
-
public async process(
|
62
|
+
public async process(prompt: string, callbacks?: AgentEvent): Promise<any> {
|
83
63
|
console.log("🔄 Processing state:");
|
84
|
-
|
85
|
-
|
86
|
-
const
|
87
|
-
|
88
|
-
const
|
89
|
-
|
90
|
-
|
91
|
-
|
92
|
-
|
93
|
-
|
94
|
-
|
95
|
-
|
96
|
-
|
97
|
-
|
98
|
-
const queueItems = QueueItemTransformer.transformActionsToQueueItems(
|
99
|
-
response.actions as ActionData[]
|
100
|
-
);
|
101
|
-
if (!queueItems) {
|
102
|
-
throw new Error("No queue items found");
|
103
|
-
}
|
64
|
+
const agent = this;
|
65
|
+
const recentMessages = await this.cache.getRecentMessages();
|
66
|
+
const previousActions = await this.cache.getRecentPreviousActions(1);
|
67
|
+
|
68
|
+
const initialState: SharedState<MyContext> = {
|
69
|
+
messages: [...recentMessages, { role: "user", content: prompt }],
|
70
|
+
context: {
|
71
|
+
prompt,
|
72
|
+
processing: {
|
73
|
+
stop: false,
|
74
|
+
},
|
75
|
+
results: previousActions,
|
76
|
+
},
|
77
|
+
};
|
104
78
|
|
105
|
-
|
106
|
-
|
107
|
-
queueItems
|
108
|
-
.map((item) => (typeof item === "string" ? item : item.name))
|
109
|
-
.join(", ")
|
110
|
-
);
|
111
|
-
|
112
|
-
queueManager.addToQueue(queueItems);
|
113
|
-
console.log("\n⚡ Executing actions...");
|
114
|
-
const results = await queueManager.processQueue();
|
115
|
-
console.log("✅ Execution results:", results);
|
116
|
-
|
117
|
-
const updatedNextState: State = {
|
118
|
-
...state,
|
119
|
-
currentContext: state.currentContext,
|
120
|
-
previousActions: [...(state.previousActions || []), ...(results || [])],
|
121
|
-
};
|
79
|
+
const mainWorkflow = createMainWorkflow(agent, prompt, callbacks);
|
80
|
+
const workflow = new Workflow<MyContext>(mainWorkflow);
|
122
81
|
|
123
|
-
|
124
|
-
|
125
|
-
|
126
|
-
|
82
|
+
await workflow.execute(
|
83
|
+
initialState,
|
84
|
+
mainWorkflow.entryNode,
|
85
|
+
async (state) => {
|
86
|
+
callbacks?.onMessage && (await callbacks.onMessage(state));
|
127
87
|
}
|
128
|
-
|
129
|
-
|
130
|
-
if (countIterations >= this.config.maxIterations) {
|
131
|
-
console.log("Max iterations reached");
|
132
|
-
response.shouldContinue = false;
|
133
|
-
console.log("Forcing stop");
|
134
|
-
}
|
135
|
-
|
136
|
-
// Handle final interpretation
|
137
|
-
if (
|
138
|
-
!response.shouldContinue &&
|
139
|
-
state.previousActions?.length &&
|
140
|
-
response.interpreter
|
141
|
-
) {
|
142
|
-
console.log("\n🏁 Analysis complete - generating final interpretation");
|
143
|
-
const interpreter = this.getInterpreter(
|
144
|
-
this.config.interpreters,
|
145
|
-
response.interpreter
|
146
|
-
);
|
147
|
-
console.log("🎭 Selected Interpreter:", interpreter?.name);
|
148
|
-
console.dir(state, { depth: null });
|
149
|
-
const interpretationResult = (await interpreter?.process(
|
150
|
-
"Interpret the analysis results",
|
151
|
-
{
|
152
|
-
...state,
|
153
|
-
results: JSON.stringify(state.previousActions),
|
154
|
-
userRequest: state.currentContext,
|
155
|
-
}
|
156
|
-
)) as { response: string };
|
157
|
-
|
158
|
-
console.log("\n📊 Final Analysis:", interpretationResult.response);
|
159
|
-
|
160
|
-
const finalState: State = {
|
161
|
-
...state,
|
162
|
-
results: interpretationResult.response,
|
163
|
-
};
|
164
|
-
|
165
|
-
console.log("🔄 Final state:", finalState);
|
166
|
-
}
|
167
|
-
|
168
|
-
// Return the final response at the end of the function
|
169
|
-
const validatedActions = response.actions.map((action) => ({
|
170
|
-
...action,
|
171
|
-
parameters: action.parameters.map((param) => ({
|
172
|
-
...param,
|
173
|
-
value: param.value ?? null, // Set a default value if undefined
|
174
|
-
})),
|
175
|
-
}));
|
176
|
-
|
177
|
-
const result = {
|
178
|
-
...response,
|
179
|
-
actions: validatedActions,
|
180
|
-
results: JSON.stringify(state.previousActions),
|
181
|
-
};
|
182
|
-
if (!result.shouldContinue) {
|
183
|
-
await this.memoryManager.process(state, JSON.stringify(result));
|
184
|
-
}
|
185
|
-
return result;
|
88
|
+
);
|
186
89
|
}
|
187
90
|
|
188
|
-
|
91
|
+
public getInterpreter(interpreters: Interpreter[], name: string) {
|
189
92
|
return interpreters.find((interpreter) => interpreter.name === name);
|
190
93
|
}
|
191
94
|
|
192
|
-
public addListener(
|
193
|
-
id
|
194
|
-
url
|
195
|
-
|
196
|
-
|
197
|
-
|
198
|
-
|
95
|
+
public addListener({
|
96
|
+
id,
|
97
|
+
url,
|
98
|
+
onSubscribe,
|
99
|
+
onMessage,
|
100
|
+
}: {
|
101
|
+
id: string;
|
102
|
+
url: string;
|
103
|
+
onSubscribe: () => string;
|
104
|
+
onMessage: (data: any, agentContext: Agent) => Promise<void>;
|
105
|
+
}): void {
|
106
|
+
if (this.listeners.has(id)) {
|
199
107
|
console.warn(`WebSocket with ID ${id} already exists.`);
|
200
108
|
return;
|
201
109
|
}
|
202
110
|
|
203
111
|
const socket = new WebSocket(url);
|
204
112
|
|
205
|
-
const
|
206
|
-
await
|
113
|
+
const wrappedOnMessage = async (data: any) => {
|
114
|
+
await onMessage(data, this);
|
207
115
|
};
|
208
116
|
|
209
117
|
socket.on("open", () => {
|
210
118
|
console.log(`🔗 WebSocket connected for ID: ${id}`);
|
211
119
|
|
212
120
|
// Envoie le message d'abonnement si une factory est fournie
|
213
|
-
if (
|
214
|
-
const subscriptionMessage =
|
121
|
+
if (onSubscribe) {
|
122
|
+
const subscriptionMessage = onSubscribe();
|
215
123
|
socket.send(subscriptionMessage);
|
216
124
|
console.log(
|
217
125
|
`📡 Sent subscription message for ID ${id}:`,
|
@@ -224,7 +132,7 @@ export class Agent {
|
|
224
132
|
console.log(`📨 Message received for WebSocket ID ${id}:`, message);
|
225
133
|
try {
|
226
134
|
const data = JSON.parse(message);
|
227
|
-
await
|
135
|
+
await wrappedOnMessage(data);
|
228
136
|
} catch (error) {
|
229
137
|
console.error(`❌ Error in callback for WebSocket ID ${id}:`, error);
|
230
138
|
}
|
@@ -238,6 +146,6 @@ export class Agent {
|
|
238
146
|
console.log(`🔌 WebSocket closed for ID: ${id}`);
|
239
147
|
});
|
240
148
|
|
241
|
-
this.
|
149
|
+
this.listeners.set(id, { socket, callback: wrappedOnMessage });
|
242
150
|
}
|
243
151
|
}
|
@@ -0,0 +1,16 @@
|
|
1
|
+
import { SharedState } from "../../types";
|
2
|
+
|
3
|
+
export const hasActions = (state: SharedState<any>): boolean =>
|
4
|
+
!!state.context.actions && state.context.actions.length > 0;
|
5
|
+
|
6
|
+
export const isNotStopped = (state: SharedState<any>): boolean =>
|
7
|
+
!state.context.processing?.stop;
|
8
|
+
|
9
|
+
export const isInterpreterDefined = (state: SharedState<any>): boolean =>
|
10
|
+
!!state.context.interpreter;
|
11
|
+
|
12
|
+
export const isResultsDefined = (state: SharedState<any>): boolean =>
|
13
|
+
!!state.context.results && state.context.results.length > 0;
|
14
|
+
|
15
|
+
export const isStopped = (state: SharedState<any>): boolean =>
|
16
|
+
!!state.context.processing?.stop;
|