@ai.ntellect/core 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/.mocharc.json +1 -1
  2. package/README.md +311 -272
  3. package/dist/graph/controller.js +63 -0
  4. package/dist/graph/engine.js +563 -0
  5. package/dist/index.js +6 -6
  6. package/dist/memory/adapters/meilisearch/index.js +249 -0
  7. package/dist/memory/adapters/redis/index.js +96 -0
  8. package/dist/memory/index.js +9 -0
  9. package/dist/services/agenda.js +115 -0
  10. package/dist/services/embedding.js +40 -0
  11. package/dist/services/queue.js +99 -103
  12. package/dist/test/graph/controller.test.js +170 -0
  13. package/dist/test/graph/engine.test.js +465 -0
  14. package/dist/test/memory/adapters/meilisearch.test.js +250 -0
  15. package/dist/test/memory/adapters/redis.test.js +143 -0
  16. package/dist/test/memory/base.test.js +209 -0
  17. package/dist/test/services/agenda.test.js +230 -0
  18. package/dist/test/services/queue.test.js +258 -0
  19. package/dist/types/index.js +2 -0
  20. package/dist/utils/generate-object.js +32 -11
  21. package/dist/utils/inject-actions.js +2 -2
  22. package/dist/utils/queue-item-transformer.js +2 -2
  23. package/dist/utils/state-manager.js +20 -0
  24. package/graph/controller.ts +60 -0
  25. package/{services/workflow.ts → graph/engine.ts} +331 -113
  26. package/index.ts +7 -7
  27. package/interfaces/index.ts +119 -0
  28. package/memory/adapters/meilisearch/index.ts +286 -0
  29. package/memory/adapters/redis/index.ts +103 -0
  30. package/memory/index.ts +22 -0
  31. package/package.json +7 -2
  32. package/services/agenda.ts +48 -43
  33. package/services/embedding.ts +26 -0
  34. package/services/queue.ts +2 -29
  35. package/test/.env.test +4 -0
  36. package/test/graph/controller.test.ts +186 -0
  37. package/test/graph/engine.test.ts +563 -0
  38. package/test/memory/adapters/meilisearch.test.ts +297 -0
  39. package/test/memory/adapters/redis.test.ts +160 -0
  40. package/test/memory/base.test.ts +229 -0
  41. package/test/services/agenda.test.ts +280 -0
  42. package/test/services/queue.test.ts +286 -44
  43. package/tsconfig.json +10 -10
  44. package/types/index.ts +270 -0
  45. package/utils/generate-object.js +111 -0
  46. package/utils/header-builder.js +34 -0
  47. package/utils/inject-actions.js +16 -0
  48. package/utils/queue-item-transformer.js +24 -0
  49. package/utils/queue-item-transformer.ts +8 -11
  50. package/utils/sanitize-results.js +60 -0
  51. package/utils/schema-generator.js +46 -0
  52. package/utils/state-manager.js +20 -0
  53. package/utils/state-manager.ts +17 -12
  54. package/.nvmrc +0 -1
  55. package/README.FR.md +0 -916
  56. package/agent/index.ts +0 -151
  57. package/agent/workflow/conditions.ts +0 -16
  58. package/agent/workflow/handlers/interpreter.handler.ts +0 -48
  59. package/agent/workflow/handlers/memory.handler.ts +0 -106
  60. package/agent/workflow/handlers/orchestrator.handler.ts +0 -23
  61. package/agent/workflow/handlers/queue.handler.ts +0 -34
  62. package/agent/workflow/handlers/scheduler.handler.ts +0 -61
  63. package/agent/workflow/index.ts +0 -62
  64. package/dist/agent/index.d.ts +0 -38
  65. package/dist/agent/index.js +0 -143
  66. package/dist/agent/tools/get-rss.d.ts +0 -16
  67. package/dist/agent/tools/get-rss.js +0 -62
  68. package/dist/bull.d.ts +0 -1
  69. package/dist/bull.js +0 -9
  70. package/dist/examples/index.d.ts +0 -2
  71. package/dist/examples/index.js +0 -89
  72. package/dist/index.d.ts +0 -7
  73. package/dist/llm/interpreter/context.d.ts +0 -15
  74. package/dist/llm/interpreter/context.js +0 -89
  75. package/dist/llm/interpreter/index.d.ts +0 -21
  76. package/dist/llm/interpreter/index.js +0 -87
  77. package/dist/llm/memory-manager/context.d.ts +0 -2
  78. package/dist/llm/memory-manager/context.js +0 -22
  79. package/dist/llm/memory-manager/index.d.ts +0 -17
  80. package/dist/llm/memory-manager/index.js +0 -107
  81. package/dist/llm/orchestrator/context.d.ts +0 -2
  82. package/dist/llm/orchestrator/context.js +0 -23
  83. package/dist/llm/orchestrator/index.d.ts +0 -44
  84. package/dist/llm/orchestrator/index.js +0 -139
  85. package/dist/llm/orchestrator/types.d.ts +0 -12
  86. package/dist/memory/cache.d.ts +0 -22
  87. package/dist/memory/cache.js +0 -165
  88. package/dist/memory/persistent.d.ts +0 -57
  89. package/dist/memory/persistent.js +0 -189
  90. package/dist/services/queue.d.ts +0 -13
  91. package/dist/services/redis-cache.d.ts +0 -37
  92. package/dist/services/redis-cache.js +0 -93
  93. package/dist/services/scheduler.d.ts +0 -40
  94. package/dist/services/scheduler.js +0 -99
  95. package/dist/services/telegram-monitor.d.ts +0 -0
  96. package/dist/services/telegram-monitor.js +0 -118
  97. package/dist/t.d.ts +0 -46
  98. package/dist/t.js +0 -102
  99. package/dist/test.d.ts +0 -0
  100. package/dist/test.js +0 -438
  101. package/dist/types.d.ts +0 -258
  102. package/dist/types.js +0 -22
  103. package/dist/utils/generate-object.d.ts +0 -12
  104. package/dist/utils/header-builder.d.ts +0 -11
  105. package/dist/utils/inject-actions.d.ts +0 -2
  106. package/dist/utils/queue-item-transformer.d.ts +0 -7
  107. package/dist/utils/sanitize-results.d.ts +0 -17
  108. package/dist/utils/schema-generator.d.ts +0 -16
  109. package/examples/actions/get-rss.ts +0 -71
  110. package/examples/index.ts +0 -98
  111. package/index.html +0 -42
  112. package/llm/dynamic-condition/example.ts +0 -36
  113. package/llm/dynamic-condition/index.ts +0 -108
  114. package/llm/interpreter/context.ts +0 -94
  115. package/llm/interpreter/index.ts +0 -140
  116. package/llm/memory-manager/context.ts +0 -19
  117. package/llm/memory-manager/index.ts +0 -115
  118. package/llm/orchestrator/context.ts +0 -19
  119. package/llm/orchestrator/index.ts +0 -192
  120. package/llm/orchestrator/types.ts +0 -14
  121. package/memory/cache.ts +0 -221
  122. package/memory/persistent.ts +0 -265
  123. package/script.js +0 -167
  124. package/services/cache.ts +0 -298
  125. package/services/telegram-monitor.ts +0 -138
  126. package/t.py +0 -79
  127. package/t.ts +0 -25
  128. package/test/llm/orchestrator.test.ts +0 -47
  129. package/test/llm/synthesizer.test.ts +0 -31
  130. package/types.ts +0 -367
  131. /package/dist/{llm/orchestrator/types.js → interfaces/index.js} +0 -0
package/agent/index.ts DELETED
@@ -1,151 +0,0 @@
1
- import { LanguageModel } from "ai";
2
- import WebSocket from "ws";
3
- import { Interpreter } from "../llm/interpreter";
4
- import { MemoryManager } from "../llm/memory-manager";
5
- import { Orchestrator } from "../llm/orchestrator";
6
- import { CacheMemory } from "../memory/cache";
7
- import { PersistentMemory } from "../memory/persistent";
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";
12
-
13
- export class Agent {
14
- public readonly memoryManager: MemoryManager;
15
- public readonly cache: RedisCache;
16
- public readonly orchestrator: Orchestrator;
17
- private listeners: Map<
18
- string,
19
- { socket: WebSocket; callback: (data: any) => Promise<void> }
20
- > = new Map();
21
- public readonly config: {
22
- interpreters: Interpreter[];
23
- orchestrator: Orchestrator;
24
- memoryManager: {
25
- model: LanguageModel;
26
- memory?: {
27
- cache?: CacheMemory;
28
- persistent?: PersistentMemory;
29
- };
30
- };
31
- maxIterations: number;
32
- };
33
-
34
- constructor(config: {
35
- cache: CacheConfig;
36
- interpreters: Interpreter[];
37
- orchestrator: Orchestrator;
38
- memoryManager: {
39
- model: LanguageModel;
40
- memory?: {
41
- cache?: CacheMemory;
42
- persistent?: PersistentMemory;
43
- };
44
- };
45
- callbacks?: QueueCallbacks;
46
- maxIterations: number;
47
- }) {
48
- this.cache = new RedisCache(config.cache);
49
- this.config = config;
50
-
51
- this.memoryManager = new MemoryManager({
52
- model: config.memoryManager.model,
53
- memory: {
54
- cache: config.memoryManager.memory?.cache ?? undefined,
55
- persistent: config.memoryManager.memory?.persistent ?? undefined,
56
- },
57
- });
58
- this.orchestrator = config.orchestrator;
59
- this.config.maxIterations = 3;
60
- }
61
-
62
- public async process(prompt: string, callbacks?: AgentEvent): Promise<any> {
63
- console.log("šŸ”„ Processing state:");
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
- };
78
-
79
- const mainWorkflow = createMainWorkflow(agent, prompt, callbacks);
80
- const workflow = new Workflow<MyContext>(mainWorkflow);
81
-
82
- await workflow.execute(
83
- initialState,
84
- mainWorkflow.entryNode,
85
- async (state) => {
86
- callbacks?.onMessage && (await callbacks.onMessage(state));
87
- }
88
- );
89
- }
90
-
91
- public getInterpreter(interpreters: Interpreter[], name: string) {
92
- return interpreters.find((interpreter) => interpreter.name === name);
93
- }
94
-
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)) {
107
- console.warn(`WebSocket with ID ${id} already exists.`);
108
- return;
109
- }
110
-
111
- const socket = new WebSocket(url);
112
-
113
- const wrappedOnMessage = async (data: any) => {
114
- await onMessage(data, this);
115
- };
116
-
117
- socket.on("open", () => {
118
- console.log(`šŸ”— WebSocket connected for ID: ${id}`);
119
-
120
- // Envoie le message d'abonnement si une factory est fournie
121
- if (onSubscribe) {
122
- const subscriptionMessage = onSubscribe();
123
- socket.send(subscriptionMessage);
124
- console.log(
125
- `šŸ“” Sent subscription message for ID ${id}:`,
126
- subscriptionMessage
127
- );
128
- }
129
- });
130
-
131
- socket.on("message", async (message: string) => {
132
- console.log(`šŸ“Ø Message received for WebSocket ID ${id}:`, message);
133
- try {
134
- const data = JSON.parse(message);
135
- await wrappedOnMessage(data);
136
- } catch (error) {
137
- console.error(`āŒ Error in callback for WebSocket ID ${id}:`, error);
138
- }
139
- });
140
-
141
- socket.on("error", (error) => {
142
- console.error(`āŒ WebSocket error for ID ${id}:`, error);
143
- });
144
-
145
- socket.on("close", () => {
146
- console.log(`šŸ”Œ WebSocket closed for ID: ${id}`);
147
- });
148
-
149
- this.listeners.set(id, { socket, callback: wrappedOnMessage });
150
- }
151
- }
@@ -1,16 +0,0 @@
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;
@@ -1,48 +0,0 @@
1
- import { Agent } from "../..";
2
- import { ActionData, MyContext, SharedState } from "../../../types";
3
- import { StateManager } from "../../../utils/state-manager";
4
-
5
- export const handleInterpreter = async (
6
- sharedState: SharedState<MyContext>,
7
- agent: Agent
8
- ) => {
9
- console.log("šŸ”„ Interpreting actions");
10
- const interpreter = agent.getInterpreter(
11
- agent.config.interpreters,
12
- sharedState.context.interpreter ?? ""
13
- );
14
-
15
- if (!interpreter) {
16
- throw new Error("No interpreter found");
17
- }
18
-
19
- console.log("šŸŽ­ Selected Interpreter:", interpreter?.name);
20
- (await interpreter?.process(sharedState, async (event: any) => {
21
- console.log("šŸŽ­ Interpreter event:", event);
22
-
23
- // Store message in recent messages
24
- await agent.cache.storeMessage("assistant", event.response);
25
- })) as { response: string };
26
-
27
- const validatedActions = sharedState.context.actions?.map(
28
- (action: ActionData) => ({
29
- ...action,
30
- name: action.name || "default", // Ensure name is always defined
31
- parameters:
32
- action.parameters?.map((param: { value: string }) => ({
33
- ...param,
34
- value: param.value ?? null,
35
- })) ?? [],
36
- })
37
- );
38
-
39
- return StateManager.updateState(sharedState, {
40
- context: {
41
- actions: validatedActions,
42
- prompt: sharedState.context.prompt,
43
- processing: {
44
- stop: true,
45
- },
46
- },
47
- });
48
- };
@@ -1,106 +0,0 @@
1
- import { Agent } from "../..";
2
- import { MemoryScope, MyContext, SharedState } from "../../../types";
3
- import { StateManager } from "../../../utils/state-manager";
4
-
5
- export const handleMemory = async (
6
- sharedState: SharedState<MyContext>,
7
- agent: Agent
8
- ) => {
9
- console.log("šŸ”„ Storing memories");
10
- const recentMessages = await agent.cache.getRecentMessages();
11
-
12
- const updatedState = StateManager.updateState(sharedState, {
13
- messages: recentMessages,
14
- });
15
-
16
- await agent.memoryManager.process(updatedState, {
17
- onMemoriesGenerated: async (event) => {
18
- if (event.memories.length === 0) {
19
- return;
20
- }
21
- // Store memories after all processing is complete
22
- await Promise.all([
23
- // Store short-term memories in cache
24
- ...event.memories
25
- .filter((m: any) => m.type === "short-term")
26
- .map(async (memoryItem: any) => {
27
- await agent.cache.storeMemory(
28
- memoryItem.data,
29
- memoryItem.category,
30
- memoryItem.tags,
31
- memoryItem.ttl
32
- );
33
-
34
- const existingCacheMemories =
35
- await agent.memoryManager.memory?.cache?.findSimilarActions(
36
- memoryItem.data,
37
- {
38
- similarityThreshold: 85,
39
- maxResults: 3,
40
- scope: MemoryScope.GLOBAL,
41
- }
42
- );
43
-
44
- if (
45
- existingCacheMemories?.length &&
46
- existingCacheMemories.length > 0
47
- ) {
48
- console.log(
49
- "āš ļø Similar memory already exists in cache:",
50
- memoryItem.data
51
- );
52
- return;
53
- }
54
-
55
- await agent.memoryManager.memory?.cache?.createMemory({
56
- query: memoryItem.queryForMemory,
57
- data: memoryItem.data,
58
- ttl: memoryItem.ttl, // Use TTL from LLM
59
- });
60
- console.log("āœ… Memory stored in cache:", memoryItem.data);
61
- }),
62
-
63
- // Store long-term memories in persistent storage
64
- ...event.memories
65
- .filter((m: any) => m.type === "long-term")
66
- .map(async (memoryItem: any) => {
67
- if (!agent.memoryManager.memory?.persistent) {
68
- return;
69
- }
70
-
71
- const existingPersistentMemories =
72
- await agent.memoryManager.memory?.persistent?.findRelevantDocuments(
73
- memoryItem.data,
74
- {
75
- similarityThreshold: 85,
76
- }
77
- );
78
-
79
- if (
80
- existingPersistentMemories?.length &&
81
- existingPersistentMemories.length > 0
82
- ) {
83
- console.log(
84
- "āš ļø Similar memory already exists in persistent storage:",
85
- memoryItem.data
86
- );
87
- return;
88
- }
89
-
90
- await agent.memoryManager.memory?.persistent?.createMemory({
91
- query: memoryItem.queryForMemory,
92
- data: memoryItem.data,
93
- category: memoryItem.category,
94
- tags: memoryItem.tags,
95
- roomId: "global",
96
- createdAt: new Date(),
97
- id: crypto.randomUUID(),
98
- });
99
- console.log("āœ… Memory stored in persistent storage:", memoryItem);
100
- }),
101
- ]);
102
- },
103
- });
104
-
105
- return updatedState;
106
- };
@@ -1,23 +0,0 @@
1
- import { Agent } from "../..";
2
- import { AgentEvent, MyContext, SharedState } from "../../../types";
3
- import { StateManager } from "../../../utils/state-manager";
4
-
5
- export const handleOrchestrator = async (
6
- prompt: string,
7
- sharedState: SharedState<MyContext>,
8
- agent: Agent,
9
- callbacks?: AgentEvent
10
- ) => {
11
- try {
12
- const result = await agent.orchestrator.process(sharedState);
13
-
14
- return StateManager.updateState(sharedState, {
15
- context: {
16
- ...result,
17
- },
18
- });
19
- } catch (error) {
20
- console.error("šŸ”„ Start handler error:", error);
21
- throw error;
22
- }
23
- };
@@ -1,34 +0,0 @@
1
- import { Agent } from "../..";
2
- import { Queue } from "../../../services/queue";
3
- import { ActionData, AgentEvent, MyContext, SharedState } from "../../../types";
4
- import { QueueItemTransformer } from "../../../utils/queue-item-transformer";
5
- import { StateManager } from "../../../utils/state-manager";
6
-
7
- export const handleQueue = async (
8
- sharedState: SharedState<MyContext>,
9
- agent: Agent,
10
- callbacks?: AgentEvent
11
- ) => {
12
- console.log("šŸ”„ Queue actions:", sharedState.context.actions);
13
- const queue = new Queue(agent.config.orchestrator.tools, callbacks);
14
- const queueItems = QueueItemTransformer.transformActionsToQueueItems(
15
- sharedState.context.actions as ActionData[]
16
- );
17
- if (!queueItems) {
18
- throw new Error("No queue items found");
19
- }
20
- queue.add(queueItems);
21
- const results = await queue.execute();
22
- if (results) {
23
- await agent.cache.storePreviousActions(crypto.randomUUID(), results);
24
- }
25
-
26
- return StateManager.updateState(sharedState, {
27
- context: {
28
- results,
29
- processing: {
30
- stop: false,
31
- },
32
- },
33
- });
34
- };
@@ -1,61 +0,0 @@
1
- import { CoreMessage } from "ai";
2
- import { Agent } from "../..";
3
- import { MyContext, SharedState } from "../../../types";
4
-
5
- export const handleScheduler = async (
6
- prompt: string,
7
- sharedState: SharedState<MyContext>,
8
- agent: Agent
9
- ) => {
10
- for (const action of sharedState.context.actions ?? []) {
11
- if (action.scheduler?.isScheduled && action.scheduler?.cronExpression) {
12
- await agent.agenda.scheduleRequest(
13
- {
14
- originalRequest: prompt,
15
- cronExpression: action.scheduler.cronExpression,
16
- },
17
- {
18
- onScheduled: (id) => {
19
- console.log("šŸ”„ Scheduled action:", id);
20
- },
21
- onExecuted: async (id, originalRequest) => {
22
- console.log("šŸ”„ Executed action:", id);
23
-
24
- // Add context about when this request was scheduled
25
- const contextualRequest = `You are a scheduler.
26
- You were asked to execute this request: ${originalRequest}\n
27
- Date of the request: ${new Date().toISOString()}\n
28
- Act like if you know the request was scheduled.
29
- Don't reschedule the same action.
30
- Just execute it.`;
31
-
32
- const updatedSharedState = {
33
- ...sharedState,
34
- messages: [
35
- {
36
- role: "user",
37
- content: contextualRequest,
38
- },
39
- ...(sharedState.messages ?? []),
40
- ] as CoreMessage[],
41
- context: {
42
- ...sharedState.context,
43
- originalRequest,
44
- },
45
- };
46
-
47
- // Process the request as if it was just received
48
- const result = await agent.orchestrator.process(updatedSharedState);
49
-
50
- // Store the new actions in cache
51
- if (result.actions.length > 0) {
52
- await agent.cache.storePreviousActions(id, result.actions);
53
- }
54
- },
55
- }
56
- );
57
- }
58
- }
59
-
60
- return sharedState;
61
- };
@@ -1,62 +0,0 @@
1
- import { Agent } from "..";
2
- import { MyContext, WorkflowDefinition } from "../../types";
3
- import {
4
- hasActions,
5
- isInterpreterDefined,
6
- isNotStopped,
7
- isResultsDefined,
8
- isStopped,
9
- } from "./conditions";
10
- import { handleInterpreter } from "./handlers/interpreter.handler";
11
- import { handleMemory } from "./handlers/memory.handler";
12
- import { handleOrchestrator } from "./handlers/orchestrator.handler";
13
- import { handleQueue } from "./handlers/queue.handler";
14
- import { handleScheduler } from "./handlers/scheduler.handler";
15
-
16
- export const createMainWorkflow = (
17
- agent: Agent,
18
- prompt: string,
19
- callbacks?: any
20
- ): WorkflowDefinition<MyContext> => ({
21
- name: "agentWorkflow", // Name of the graph
22
- entryNode: "makeDecision", // Entry node
23
- nodes: {
24
- makeDecision: {
25
- name: "makeDecision",
26
- description: "Make a decision following the environment",
27
- execute: async (state) =>
28
- handleOrchestrator(prompt, state, agent, callbacks),
29
- condition: (state) => isNotStopped(state), // Check if the agent is not stopped
30
- next: ["checkEnvironment", "scheduleActions", "interpretResults"], // Next nodes to execute
31
- },
32
- checkEnvironment: {
33
- name: "checkEnvironment", // Check the environment
34
- description: "Check the environment for any actions to handle",
35
- execute: async (state) => handleQueue(state, agent, callbacks),
36
- condition: (state) => hasActions(state) && isNotStopped(state), // Check if there are actions to handle and the agent is not stopped
37
- next: ["makeDecision"],
38
- },
39
- scheduleActions: {
40
- name: "scheduleActions",
41
- description: "Schedule actions for the future",
42
- execute: async (state) => handleScheduler(prompt, state, agent),
43
- condition: (state) => hasActions(state), // Check if there are actions to schedule
44
- },
45
- interpretResults: {
46
- name: "interpretResults",
47
- description: "Interpret the results of the actions",
48
- execute: async (state) => handleInterpreter(state, agent),
49
- condition: (state) =>
50
- isInterpreterDefined(state) && // Check if interpreter is defined
51
- isResultsDefined(state) && // Check if results are defined
52
- isStopped(state), // Check if processing is stopped
53
- next: ["saveMemory"],
54
- },
55
- saveMemory: {
56
- name: "saveMemory",
57
- description: "Save memory",
58
- execute: async (state) => handleMemory(state, agent),
59
- condition: (state) => isResultsDefined(state), // Check if results are defined
60
- },
61
- },
62
- });
@@ -1,38 +0,0 @@
1
- import { LanguageModel } from "ai";
2
- import { Interpreter } from "../llm/interpreter";
3
- import { State } from "../llm/orchestrator/types";
4
- import { CacheMemory } from "../memory/cache";
5
- import { PersistentMemory } from "../memory/persistent";
6
- import { CacheConfig } from "../services/redis-cache";
7
- import { ActionSchema, QueueCallbacks } from "../types";
8
- export declare class Agent {
9
- private readonly agent;
10
- private readonly memoryManager;
11
- private readonly cache;
12
- private listeners;
13
- private readonly config;
14
- constructor(config: {
15
- cache: CacheConfig;
16
- orchestrator: {
17
- model: LanguageModel;
18
- tools: ActionSchema[];
19
- memory?: {
20
- cache?: CacheMemory;
21
- persistent?: PersistentMemory;
22
- };
23
- };
24
- interpreters: Interpreter[];
25
- memoryManager: {
26
- model: LanguageModel;
27
- memory?: {
28
- cache?: CacheMemory;
29
- persistent?: PersistentMemory;
30
- };
31
- };
32
- callbacks?: QueueCallbacks;
33
- maxIterations: number;
34
- });
35
- process(state: State, callbacks?: QueueCallbacks): Promise<any>;
36
- private getInterpreter;
37
- addListener(id: string, url: string, subscriptionMessageFactory: () => string, callback: (data: any, agentContext: Agent) => Promise<void>): void;
38
- }
@@ -1,143 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.Agent = void 0;
7
- const ws_1 = __importDefault(require("ws"));
8
- const memory_manager_1 = require("../llm/memory-manager");
9
- const orchestrator_1 = require("../llm/orchestrator");
10
- const queue_1 = require("../services/queue");
11
- const redis_cache_1 = require("../services/redis-cache");
12
- const queue_item_transformer_1 = require("../utils/queue-item-transformer");
13
- class Agent {
14
- constructor(config) {
15
- this.listeners = new Map();
16
- this.cache = new redis_cache_1.RedisCache(config.cache);
17
- this.config = config;
18
- this.agent = new orchestrator_1.AgentRuntime(config.orchestrator.model, config.orchestrator.tools, config.interpreters, config.cache, config.orchestrator.memory);
19
- this.memoryManager = new memory_manager_1.MemoryManager({
20
- model: config.memoryManager.model,
21
- memory: {
22
- cache: config.memoryManager.memory?.cache ?? undefined,
23
- persistent: config.memoryManager.memory?.persistent ?? undefined,
24
- },
25
- });
26
- this.config.maxIterations = 3;
27
- }
28
- async process(state, callbacks) {
29
- console.log("šŸ”„ Processing state:");
30
- console.dir(state, { depth: null });
31
- let countIterations = 0;
32
- const response = await this.agent.process(state);
33
- const unscheduledActions = response.actions.filter((action) => !action.scheduler?.isScheduled);
34
- // Execute actions if needed
35
- if (unscheduledActions?.length > 0 && response.shouldContinue) {
36
- console.log("\nšŸ“‹ Processing action queue");
37
- const queueManager = new queue_1.ActionQueueManager(this.config.orchestrator.tools, callbacks);
38
- const queueItems = queue_item_transformer_1.QueueItemTransformer.transformActionsToQueueItems(response.actions);
39
- if (!queueItems) {
40
- throw new Error("No queue items found");
41
- }
42
- console.log("šŸ“‹ Actions to execute:", queueItems
43
- .map((item) => (typeof item === "string" ? item : item.name))
44
- .join(", "));
45
- queueManager.addToQueue(queueItems);
46
- console.log("\n⚔ Executing actions...");
47
- const results = await queueManager.processQueue();
48
- console.log("āœ… Execution results:", results);
49
- const updatedNextState = {
50
- ...state,
51
- currentContext: state.currentContext,
52
- previousActions: [...(state.previousActions || []), ...(results || [])],
53
- };
54
- console.log("\nšŸ” Recursively processing with updated state");
55
- countIterations++;
56
- if (countIterations < this.config.maxIterations) {
57
- return this.process(updatedNextState);
58
- }
59
- }
60
- if (countIterations >= this.config.maxIterations) {
61
- console.log("Max iterations reached");
62
- response.shouldContinue = false;
63
- console.log("Forcing stop");
64
- }
65
- // Handle final interpretation
66
- if (!response.shouldContinue &&
67
- state.previousActions?.length &&
68
- response.interpreter) {
69
- console.log("\nšŸ Analysis complete - generating final interpretation");
70
- const interpreter = this.getInterpreter(this.config.interpreters, response.interpreter);
71
- console.log("šŸŽ­ Selected Interpreter:", interpreter?.name);
72
- console.dir(state, { depth: null });
73
- const interpretationResult = (await interpreter?.process("Interpret the analysis results", {
74
- ...state,
75
- results: JSON.stringify(state.previousActions),
76
- userRequest: state.currentContext,
77
- }));
78
- console.log("\nšŸ“Š Final Analysis:", interpretationResult.response);
79
- const finalState = {
80
- ...state,
81
- results: interpretationResult.response,
82
- };
83
- console.log("šŸ”„ Final state:", finalState);
84
- }
85
- // Return the final response at the end of the function
86
- const validatedActions = response.actions.map((action) => ({
87
- ...action,
88
- parameters: action.parameters.map((param) => ({
89
- ...param,
90
- value: param.value ?? null, // Set a default value if undefined
91
- })),
92
- }));
93
- const result = {
94
- ...response,
95
- actions: validatedActions,
96
- results: JSON.stringify(state.previousActions),
97
- };
98
- if (!result.shouldContinue) {
99
- await this.memoryManager.process(state, JSON.stringify(result));
100
- }
101
- return result;
102
- }
103
- getInterpreter(interpreters, name) {
104
- return interpreters.find((interpreter) => interpreter.name === name);
105
- }
106
- addListener(id, url, subscriptionMessageFactory, callback) {
107
- if (this.listeners.has(id)) {
108
- console.warn(`WebSocket with ID ${id} already exists.`);
109
- return;
110
- }
111
- const socket = new ws_1.default(url);
112
- const wrappedCallback = async (data) => {
113
- await callback(data, this);
114
- };
115
- socket.on("open", () => {
116
- console.log(`šŸ”— WebSocket connected for ID: ${id}`);
117
- // Envoie le message d'abonnement si une factory est fournie
118
- if (subscriptionMessageFactory) {
119
- const subscriptionMessage = subscriptionMessageFactory();
120
- socket.send(subscriptionMessage);
121
- console.log(`šŸ“” Sent subscription message for ID ${id}:`, subscriptionMessage);
122
- }
123
- });
124
- socket.on("message", async (message) => {
125
- console.log(`šŸ“Ø Message received for WebSocket ID ${id}:`, message);
126
- try {
127
- const data = JSON.parse(message);
128
- await wrappedCallback(data);
129
- }
130
- catch (error) {
131
- console.error(`āŒ Error in callback for WebSocket ID ${id}:`, error);
132
- }
133
- });
134
- socket.on("error", (error) => {
135
- console.error(`āŒ WebSocket error for ID ${id}:`, error);
136
- });
137
- socket.on("close", () => {
138
- console.log(`šŸ”Œ WebSocket closed for ID: ${id}`);
139
- });
140
- this.listeners.set(id, { socket, callback: wrappedCallback });
141
- }
142
- }
143
- exports.Agent = Agent;