@ai.ntellect/core 0.3.1 ā 0.3.3
Sign up to get free protection for your applications and to get access to all the features.
- package/agent/index.ts +43 -7
- package/dist/agent/index.d.ts +5 -1
- package/dist/agent/index.js +25 -9
- package/dist/llm/evaluator/context.js +7 -5
- package/dist/llm/evaluator/index.js +8 -9
- package/dist/llm/interpreter/context.js +1 -1
- package/dist/llm/orchestrator/context.d.ts +1 -1
- package/dist/llm/orchestrator/context.js +4 -6
- package/dist/llm/orchestrator/index.js +1 -1
- package/dist/memory/cache.d.ts +0 -1
- package/dist/memory/cache.js +4 -21
- package/dist/memory/persistent.d.ts +4 -10
- package/dist/memory/persistent.js +17 -53
- package/dist/services/scheduler.d.ts +17 -0
- package/dist/services/scheduler.js +121 -0
- package/dist/services/telegram-monitor.d.ts +15 -0
- package/dist/services/telegram-monitor.js +102 -0
- package/dist/test.d.ts +0 -167
- package/dist/test.js +503 -372
- package/dist/types.d.ts +22 -2
- package/llm/evaluator/index.ts +3 -4
- package/memory/cache.ts +4 -24
- package/memory/persistent.ts +14 -64
- package/package.json +1 -1
- package/services/scheduler.ts +167 -0
- package/services/telegram-monitor.ts +138 -0
- package/types.ts +24 -2
package/agent/index.ts
CHANGED
@@ -3,7 +3,15 @@ import { Interpreter } from "../llm/interpreter";
|
|
3
3
|
import { Orchestrator } from "../llm/orchestrator";
|
4
4
|
import { CacheMemory } from "../memory/cache";
|
5
5
|
import { PersistentMemory } from "../memory/persistent";
|
6
|
-
import {
|
6
|
+
import { ActionQueueManager } from "../services/queue";
|
7
|
+
import { ActionScheduler } from "../services/scheduler";
|
8
|
+
import {
|
9
|
+
ActionSchema,
|
10
|
+
AgentEvent,
|
11
|
+
MemoryScope,
|
12
|
+
QueueResult,
|
13
|
+
ScheduledAction,
|
14
|
+
} from "../types";
|
7
15
|
import { QueueItemTransformer } from "../utils/queue-item-transformer";
|
8
16
|
import { ResultSanitizer } from "../utils/sanitize-results";
|
9
17
|
import { ActionHandler } from "./handlers/ActionHandler";
|
@@ -21,6 +29,7 @@ export class Agent {
|
|
21
29
|
private evaluatorIteration = 0;
|
22
30
|
private accumulatedResults: string = "";
|
23
31
|
private currentInterpreter: Interpreter | undefined;
|
32
|
+
private readonly scheduler: ActionScheduler;
|
24
33
|
|
25
34
|
constructor({
|
26
35
|
orchestrator,
|
@@ -45,18 +54,27 @@ export class Agent {
|
|
45
54
|
this.maxEvaluatorIteration = maxEvaluatorIteration;
|
46
55
|
this.actionHandler = new ActionHandler();
|
47
56
|
this.accumulatedResults = "";
|
57
|
+
this.scheduler = new ActionScheduler(
|
58
|
+
new ActionQueueManager(this.orchestrator.tools),
|
59
|
+
this.orchestrator
|
60
|
+
);
|
48
61
|
}
|
49
62
|
|
50
63
|
async process(prompt: string, events: AgentEvent): Promise<any> {
|
51
64
|
this.accumulatedResults = "";
|
52
65
|
this.evaluatorIteration = 0;
|
53
66
|
console.log("Requesting orchestrator for actions..");
|
54
|
-
const
|
55
|
-
|
56
|
-
|
57
|
-
|
58
|
-
|
59
|
-
|
67
|
+
const parsedPrompt = JSON.parse(prompt);
|
68
|
+
const promptOnly = parsedPrompt.userRequest;
|
69
|
+
const cacheMemories = await this.memory.cache?.findSimilarActions(
|
70
|
+
promptOnly,
|
71
|
+
{
|
72
|
+
similarityThreshold: 70,
|
73
|
+
maxResults: 5,
|
74
|
+
userId: "1",
|
75
|
+
scope: MemoryScope.GLOBAL,
|
76
|
+
}
|
77
|
+
);
|
60
78
|
console.log("ā
RECENT_ACTIONS: ", cacheMemories);
|
61
79
|
|
62
80
|
const persistentMemory = await this.memory.persistent.findRelevantDocuments(
|
@@ -221,4 +239,22 @@ export class Agent {
|
|
221
239
|
const sanitizedResults = ResultSanitizer.sanitize(formattedResults);
|
222
240
|
return sanitizedResults;
|
223
241
|
}
|
242
|
+
|
243
|
+
async scheduleAction(
|
244
|
+
action: ActionSchema,
|
245
|
+
scheduledTime: Date,
|
246
|
+
userId: string,
|
247
|
+
recurrence?: ScheduledAction["recurrence"]
|
248
|
+
): Promise<string> {
|
249
|
+
return this.scheduler.scheduleAction(
|
250
|
+
action,
|
251
|
+
scheduledTime,
|
252
|
+
userId,
|
253
|
+
recurrence
|
254
|
+
);
|
255
|
+
}
|
256
|
+
|
257
|
+
async cancelScheduledAction(actionId: string): Promise<boolean> {
|
258
|
+
return this.scheduler.cancelScheduledAction(actionId);
|
259
|
+
}
|
224
260
|
}
|
package/dist/agent/index.d.ts
CHANGED
@@ -2,7 +2,7 @@ import { Interpreter } from "../llm/interpreter";
|
|
2
2
|
import { Orchestrator } from "../llm/orchestrator";
|
3
3
|
import { CacheMemory } from "../memory/cache";
|
4
4
|
import { PersistentMemory } from "../memory/persistent";
|
5
|
-
import { AgentEvent } from "../types";
|
5
|
+
import { ActionSchema, AgentEvent, ScheduledAction } from "../types";
|
6
6
|
export declare class Agent {
|
7
7
|
private readonly actionHandler;
|
8
8
|
private readonly orchestrator;
|
@@ -12,6 +12,8 @@ export declare class Agent {
|
|
12
12
|
private readonly maxEvaluatorIteration;
|
13
13
|
private evaluatorIteration;
|
14
14
|
private accumulatedResults;
|
15
|
+
private currentInterpreter;
|
16
|
+
private readonly scheduler;
|
15
17
|
constructor({ orchestrator, interpreters, memory, stream, maxEvaluatorIteration, }: {
|
16
18
|
orchestrator: Orchestrator;
|
17
19
|
interpreters: Interpreter[];
|
@@ -28,4 +30,6 @@ export declare class Agent {
|
|
28
30
|
private interpreterResult;
|
29
31
|
private transformActions;
|
30
32
|
private formatResults;
|
33
|
+
scheduleAction(action: ActionSchema, scheduledTime: Date, userId: string, recurrence?: ScheduledAction["recurrence"]): Promise<string>;
|
34
|
+
cancelScheduledAction(actionId: string): Promise<boolean>;
|
31
35
|
}
|
package/dist/agent/index.js
CHANGED
@@ -2,6 +2,8 @@
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
3
3
|
exports.Agent = void 0;
|
4
4
|
const evaluator_1 = require("../llm/evaluator");
|
5
|
+
const queue_1 = require("../services/queue");
|
6
|
+
const scheduler_1 = require("../services/scheduler");
|
5
7
|
const types_1 = require("../types");
|
6
8
|
const queue_item_transformer_1 = require("../utils/queue-item-transformer");
|
7
9
|
const sanitize_results_1 = require("../utils/sanitize-results");
|
@@ -17,19 +19,26 @@ class Agent {
|
|
17
19
|
this.maxEvaluatorIteration = maxEvaluatorIteration;
|
18
20
|
this.actionHandler = new ActionHandler_1.ActionHandler();
|
19
21
|
this.accumulatedResults = "";
|
22
|
+
this.scheduler = new scheduler_1.ActionScheduler(new queue_1.ActionQueueManager(this.orchestrator.tools), this.orchestrator);
|
20
23
|
}
|
21
24
|
async process(prompt, events) {
|
22
25
|
this.accumulatedResults = "";
|
23
26
|
this.evaluatorIteration = 0;
|
24
27
|
console.log("Requesting orchestrator for actions..");
|
25
|
-
const
|
28
|
+
const parsedPrompt = JSON.parse(prompt);
|
29
|
+
const promptOnly = parsedPrompt.userRequest;
|
30
|
+
const cacheMemories = await this.memory.cache?.findSimilarActions(promptOnly, {
|
26
31
|
similarityThreshold: 70,
|
27
32
|
maxResults: 5,
|
28
33
|
userId: "1",
|
29
34
|
scope: types_1.MemoryScope.GLOBAL,
|
30
35
|
});
|
31
36
|
console.log("ā
RECENT_ACTIONS: ", cacheMemories);
|
32
|
-
const
|
37
|
+
const persistentMemory = await this.memory.persistent.findRelevantDocuments(prompt, {
|
38
|
+
similarityThreshold: 80,
|
39
|
+
});
|
40
|
+
console.log("ā
PERSISTENT_MEMORY: ", persistentMemory);
|
41
|
+
const request = await this.orchestrator.process(prompt, `## RECENT_ACTIONS: ${JSON.stringify(cacheMemories)} ## PERSISTENT_MEMORY: ${JSON.stringify(persistentMemory)} ## CURRENT_RESULTS: ${this.accumulatedResults}`);
|
33
42
|
events.onMessage?.(request);
|
34
43
|
return request.actions.length > 0
|
35
44
|
? this.handleActions({
|
@@ -59,12 +68,12 @@ class Agent {
|
|
59
68
|
return this.interpreterResult({
|
60
69
|
data: this.accumulatedResults,
|
61
70
|
initialPrompt,
|
62
|
-
interpreter: this.
|
71
|
+
interpreter: this.currentInterpreter,
|
63
72
|
});
|
64
73
|
}
|
65
74
|
const evaluator = new evaluator_1.Evaluator(this.orchestrator.tools, this.memory, this.interpreters);
|
66
|
-
// const sanitizedResults = ResultSanitizer.sanitize(this.accumulatedResults);
|
67
75
|
const evaluation = await evaluator.process(initialPrompt, this.accumulatedResults);
|
76
|
+
this.currentInterpreter = this.getInterpreter(this.interpreters, evaluation.interpreter);
|
68
77
|
events.onMessage?.(evaluation);
|
69
78
|
if (evaluation.isNextActionNeeded) {
|
70
79
|
this.evaluatorIteration++;
|
@@ -73,21 +82,22 @@ class Agent {
|
|
73
82
|
actions: evaluation.nextActionsNeeded,
|
74
83
|
}, events);
|
75
84
|
}
|
76
|
-
const interpreter = this.getInterpreter(this.interpreters, evaluation.interpreter);
|
77
|
-
if (!interpreter) {
|
78
|
-
throw new Error("Interpreter not found");
|
79
|
-
}
|
80
85
|
return this.interpreterResult({
|
81
86
|
data: this.accumulatedResults,
|
82
87
|
initialPrompt,
|
83
|
-
interpreter,
|
88
|
+
interpreter: this.currentInterpreter,
|
84
89
|
});
|
85
90
|
}
|
86
91
|
getInterpreter(interpreters, name) {
|
92
|
+
console.log({ interpreters, name });
|
87
93
|
return interpreters.find((interpreter) => interpreter.name === name);
|
88
94
|
}
|
89
95
|
async interpreterResult(actionsResult) {
|
90
96
|
const { interpreter, initialPrompt, data } = actionsResult;
|
97
|
+
if (!interpreter) {
|
98
|
+
throw new Error("Interpreter not found");
|
99
|
+
}
|
100
|
+
console.log("ā
INTERPRETER: ", interpreter.name);
|
91
101
|
return this.stream
|
92
102
|
? (await interpreter.streamProcess(initialPrompt, {
|
93
103
|
userRequest: initialPrompt,
|
@@ -112,5 +122,11 @@ class Agent {
|
|
112
122
|
const sanitizedResults = sanitize_results_1.ResultSanitizer.sanitize(formattedResults);
|
113
123
|
return sanitizedResults;
|
114
124
|
}
|
125
|
+
async scheduleAction(action, scheduledTime, userId, recurrence) {
|
126
|
+
return this.scheduler.scheduleAction(action, scheduledTime, userId, recurrence);
|
127
|
+
}
|
128
|
+
async cancelScheduledAction(actionId) {
|
129
|
+
return this.scheduler.cancelScheduledAction(actionId);
|
130
|
+
}
|
115
131
|
}
|
116
132
|
exports.Agent = Agent;
|
@@ -3,14 +3,16 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.evaluatorContext = void 0;
|
4
4
|
exports.evaluatorContext = {
|
5
5
|
behavior: {
|
6
|
-
language: "
|
7
|
-
role: "Your role is to
|
6
|
+
language: "same_as_user",
|
7
|
+
role: "Your role is to ensure the goal will be achieved and make a response or suggest next actions.",
|
8
8
|
guidelines: {
|
9
9
|
important: [
|
10
|
-
"Verify if all
|
11
|
-
"Check if the results align with the initial goal.",
|
10
|
+
"Verify if all actions were executed successfully (actionsAlreadyDone).",
|
11
|
+
"Check if the results align with the initial goal (explain in 'why' field).",
|
12
|
+
"Suggest next actions in 'nextActionsNeeded' if the goal is not achieved and if actions in 'actionsAlreadyDone' are not enough.",
|
12
13
|
"If you retrieved the informations from your internal knowledge base, no need to store them in 'extraInformationsToStore'.",
|
13
|
-
"Store ONLY
|
14
|
+
"Store ONLY new needed informations in 'extraInformationsToStore'.",
|
15
|
+
"Choose the most relevant informations and memory type: episodic, semantic, or procedural.",
|
14
16
|
],
|
15
17
|
warnings: [
|
16
18
|
"NEVER store an old data you retrieve from your internal knowledge base.",
|
@@ -43,8 +43,8 @@ class Evaluator {
|
|
43
43
|
const response = await (0, ai_1.generateObject)({
|
44
44
|
model: this.model,
|
45
45
|
schema: zod_1.z.object({
|
46
|
-
|
47
|
-
|
46
|
+
requestLanguage: zod_1.z.string(),
|
47
|
+
actionsAlreadyDone: zod_1.z.array(zod_1.z.string()),
|
48
48
|
extraInformationsToStore: zod_1.z.array(zod_1.z.object({
|
49
49
|
memoryType: zod_1.z.enum(["episodic", "semantic", "procedural"]),
|
50
50
|
queryForData: zod_1.z.string(),
|
@@ -80,7 +80,7 @@ class Evaluator {
|
|
80
80
|
console.log("\nš Processing memory item:");
|
81
81
|
console.log("Type:", item.memoryType);
|
82
82
|
console.log("Content:", item.queryForData);
|
83
|
-
const memories = await this.memory.persistent.
|
83
|
+
const memories = await this.memory.persistent.findRelevantDocuments(item.queryForData, {
|
84
84
|
similarityThreshold: 70,
|
85
85
|
});
|
86
86
|
if (memories.length > 0) {
|
@@ -93,7 +93,7 @@ class Evaluator {
|
|
93
93
|
purpose: item.memoryType,
|
94
94
|
query: item.queryForData,
|
95
95
|
data: item.data,
|
96
|
-
|
96
|
+
roomId: "global",
|
97
97
|
createdAt: new Date(),
|
98
98
|
});
|
99
99
|
}
|
@@ -104,10 +104,9 @@ class Evaluator {
|
|
104
104
|
cacheMemory.createMemory({
|
105
105
|
content: prompt,
|
106
106
|
type: types_1.MemoryType.ACTION,
|
107
|
-
data: validatedResponse.
|
108
|
-
scope: types_1.MemoryScope.GLOBAL,
|
107
|
+
data: validatedResponse.actionsAlreadyDone,
|
109
108
|
});
|
110
|
-
console.log("ā
Workflow actions completed stored in cache", prompt, validatedResponse.
|
109
|
+
console.log("ā
Workflow actions completed stored in cache", prompt, validatedResponse.actionsAlreadyDone);
|
111
110
|
}
|
112
111
|
console.log("\nā
Evaluation completed");
|
113
112
|
console.log("ā".repeat(50));
|
@@ -123,7 +122,7 @@ class Evaluator {
|
|
123
122
|
if (error.value.extraInformationsToStore.length > 0) {
|
124
123
|
for (const item of error.value.extraInformationsToStore) {
|
125
124
|
// Check if the item is already in the memory
|
126
|
-
const memories = await this.memory.persistent.
|
125
|
+
const memories = await this.memory.persistent.findRelevantDocuments(item.content);
|
127
126
|
if (memories.length === 0) {
|
128
127
|
console.log("Adding to memory", {
|
129
128
|
query: item.content,
|
@@ -134,7 +133,7 @@ class Evaluator {
|
|
134
133
|
purpose: "importantToRemember",
|
135
134
|
query: item.content,
|
136
135
|
data: item.data,
|
137
|
-
|
136
|
+
roomId: "global",
|
138
137
|
createdAt: new Date(),
|
139
138
|
});
|
140
139
|
}
|
@@ -3,7 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.marketInterpreterContext = exports.securityInterpreterContext = exports.generalInterpreterContext = void 0;
|
4
4
|
exports.generalInterpreterContext = {
|
5
5
|
role: "You are the general assistant. Your role is to provide a clear and factual analysis of the results.",
|
6
|
-
language: "
|
6
|
+
language: "same_as_user",
|
7
7
|
guidelines: {
|
8
8
|
important: [],
|
9
9
|
warnings: [],
|
@@ -3,18 +3,16 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.orchestratorContext = void 0;
|
4
4
|
exports.orchestratorContext = {
|
5
5
|
behavior: {
|
6
|
-
language: "
|
7
|
-
role: "
|
6
|
+
language: "same_as_user",
|
7
|
+
role: "Your role is to determine what actions are needed to achieve the user goal.",
|
8
8
|
guidelines: {
|
9
9
|
important: [
|
10
10
|
"If there is no action to do, you must answer in the 'answer' field.",
|
11
11
|
"If some parameters are not clear or missing, don't add the action, YOU MUST ask the user for them.",
|
12
|
-
"
|
12
|
+
"For QUESTIONS or ANALYSIS, search first in your internal knowledge base before using actions.",
|
13
13
|
"For ON-CHAIN actions, just use the useful actions.",
|
14
|
-
"For QUESTIONS or ANALYSIS, you MUST search in your cache memory or/and internal knowledge base.",
|
15
|
-
"NEVER repeat same actions if the user doesn't ask for it.",
|
16
14
|
],
|
17
|
-
warnings: [],
|
15
|
+
warnings: ["NEVER repeat same actions if the user doesn't ask for it."],
|
18
16
|
},
|
19
17
|
},
|
20
18
|
};
|
@@ -20,7 +20,7 @@ class Orchestrator {
|
|
20
20
|
query: zod_1.z.string(),
|
21
21
|
}),
|
22
22
|
execute: async ({ query }) => {
|
23
|
-
const persistentMemories = await this.memory.persistent.
|
23
|
+
const persistentMemories = await this.memory.persistent.findRelevantDocuments(query, {
|
24
24
|
similarityThreshold: 70,
|
25
25
|
});
|
26
26
|
return `# LONG_TERM_MEMORY: ${JSON.stringify(persistentMemories)}`;
|
package/dist/memory/cache.d.ts
CHANGED
package/dist/memory/cache.js
CHANGED
@@ -31,14 +31,8 @@ class CacheMemory {
|
|
31
31
|
console.error("ā Failed to connect to Redis:", error);
|
32
32
|
}
|
33
33
|
}
|
34
|
-
getMemoryKey(scope, userId) {
|
35
|
-
if (scope === types_1.MemoryScope.GLOBAL) {
|
36
|
-
return `${this.CACHE_PREFIX}global:`;
|
37
|
-
}
|
38
|
-
return `${this.CACHE_PREFIX}user:${userId}:`;
|
39
|
-
}
|
40
34
|
async storeMemory(memory) {
|
41
|
-
const prefix = this.
|
35
|
+
const prefix = this.CACHE_PREFIX;
|
42
36
|
const key = `${prefix}${memory.id}`;
|
43
37
|
const result = await this.redis.set(key, JSON.stringify(memory), {
|
44
38
|
EX: this.CACHE_TTL,
|
@@ -87,20 +81,9 @@ class CacheMemory {
|
|
87
81
|
return results;
|
88
82
|
}
|
89
83
|
async getAllMemories(scope, userId) {
|
90
|
-
|
91
|
-
|
92
|
-
|
93
|
-
const globalKeys = await this.redis.keys(`${globalPrefix}*`);
|
94
|
-
const globalPatterns = await this.getMemoriesFromKeys(globalKeys);
|
95
|
-
patterns = patterns.concat(globalPatterns);
|
96
|
-
}
|
97
|
-
if (userId && (!scope || scope === types_1.MemoryScope.USER)) {
|
98
|
-
const userPrefix = this.getMemoryKey(types_1.MemoryScope.USER, userId);
|
99
|
-
const userKeys = await this.redis.keys(`${userPrefix}*`);
|
100
|
-
const userPatterns = await this.getMemoriesFromKeys(userKeys);
|
101
|
-
patterns = patterns.concat(userPatterns);
|
102
|
-
}
|
103
|
-
return patterns;
|
84
|
+
const keys = await this.redis.keys(`${this.CACHE_PREFIX}*`);
|
85
|
+
const memories = await this.getMemoriesFromKeys(keys);
|
86
|
+
return memories;
|
104
87
|
}
|
105
88
|
async getMemoriesFromKeys(keys) {
|
106
89
|
const memories = [];
|
@@ -29,10 +29,6 @@ export declare class PersistentMemory {
|
|
29
29
|
* Make API request to Meilisearch
|
30
30
|
*/
|
31
31
|
private _makeRequest;
|
32
|
-
/**
|
33
|
-
* Get index name based on scope and userId
|
34
|
-
*/
|
35
|
-
private _getIndexName;
|
36
32
|
/**
|
37
33
|
* Get or create an index with proper settings
|
38
34
|
*/
|
@@ -45,17 +41,15 @@ export declare class PersistentMemory {
|
|
45
41
|
/**
|
46
42
|
* Find best matching memories
|
47
43
|
*/
|
48
|
-
|
49
|
-
createdAt: string;
|
50
|
-
data: any;
|
51
|
-
purpose: string;
|
44
|
+
findRelevantDocuments(query: string, options?: SearchOptions): Promise<{
|
52
45
|
query: string;
|
53
|
-
|
46
|
+
data: any;
|
54
47
|
similarityPercentage: number;
|
48
|
+
createdAt: string;
|
55
49
|
}[]>;
|
56
50
|
/**
|
57
51
|
* Delete memories for a given scope and user
|
58
52
|
*/
|
59
|
-
deleteMemories(
|
53
|
+
deleteMemories(): Promise<unknown>;
|
60
54
|
}
|
61
55
|
export {};
|
@@ -4,7 +4,6 @@ exports.PersistentMemory = void 0;
|
|
4
4
|
const openai_1 = require("@ai-sdk/openai");
|
5
5
|
const ai_1 = require("ai");
|
6
6
|
const text_splitter_1 = require("langchain/text_splitter");
|
7
|
-
const types_1 = require("../types");
|
8
7
|
/**
|
9
8
|
* Handles persistent memory storage using Meilisearch API
|
10
9
|
*/
|
@@ -12,16 +11,14 @@ class PersistentMemory {
|
|
12
11
|
constructor(options) {
|
13
12
|
this.host = options.host;
|
14
13
|
this.apiKey = options.apiKey;
|
15
|
-
this.INDEX_PREFIX = options.indexPrefix || "
|
14
|
+
this.INDEX_PREFIX = options.indexPrefix || "memory";
|
16
15
|
}
|
17
16
|
/**
|
18
17
|
* Initialize indexes
|
19
18
|
*/
|
20
19
|
async init() {
|
21
20
|
// Create global index
|
22
|
-
await this._getOrCreateIndex(this.
|
23
|
-
// Create user index
|
24
|
-
await this._getOrCreateIndex(this._getIndexName(types_1.MemoryScope.USER));
|
21
|
+
await this._getOrCreateIndex(this.INDEX_PREFIX);
|
25
22
|
}
|
26
23
|
/**
|
27
24
|
* Make API request to Meilisearch
|
@@ -42,15 +39,6 @@ class PersistentMemory {
|
|
42
39
|
}
|
43
40
|
return response.json();
|
44
41
|
}
|
45
|
-
/**
|
46
|
-
* Get index name based on scope and userId
|
47
|
-
*/
|
48
|
-
_getIndexName(scope, userId) {
|
49
|
-
if (scope === "global") {
|
50
|
-
return `${this.INDEX_PREFIX}global`;
|
51
|
-
}
|
52
|
-
return `${this.INDEX_PREFIX}user_${userId}`;
|
53
|
-
}
|
54
42
|
/**
|
55
43
|
* Get or create an index with proper settings
|
56
44
|
*/
|
@@ -102,15 +90,14 @@ class PersistentMemory {
|
|
102
90
|
* Store a memory in the database
|
103
91
|
*/
|
104
92
|
async createMemory(memory) {
|
105
|
-
|
106
|
-
await this._getOrCreateIndex(indexName);
|
93
|
+
await this._getOrCreateIndex(memory.roomId);
|
107
94
|
const chunks = await this.processContent(memory.data);
|
108
95
|
const document = {
|
109
96
|
...memory,
|
110
97
|
chunks,
|
111
98
|
createdAt: memory.createdAt.toISOString(),
|
112
99
|
};
|
113
|
-
const response = await this._makeRequest(`/indexes/${
|
100
|
+
const response = await this._makeRequest(`/indexes/${this.INDEX_PREFIX}/documents`, {
|
114
101
|
method: "POST",
|
115
102
|
body: JSON.stringify([document]),
|
116
103
|
});
|
@@ -120,7 +107,7 @@ class PersistentMemory {
|
|
120
107
|
/**
|
121
108
|
* Find best matching memories
|
122
109
|
*/
|
123
|
-
async
|
110
|
+
async findRelevantDocuments(query, options = {}) {
|
124
111
|
console.log("\nš Searching in persistent memory");
|
125
112
|
console.log("Query:", query);
|
126
113
|
console.log("Options:", JSON.stringify(options, null, 2));
|
@@ -130,47 +117,29 @@ class PersistentMemory {
|
|
130
117
|
value: query,
|
131
118
|
});
|
132
119
|
const searchResults = [];
|
133
|
-
|
134
|
-
|
135
|
-
const
|
136
|
-
console.log("\nš Searching in global index:", globalIndex);
|
137
|
-
try {
|
138
|
-
const globalResults = await this._makeRequest(`/indexes/${globalIndex}/search`, {
|
139
|
-
method: "POST",
|
140
|
-
body: JSON.stringify({ q: query }),
|
141
|
-
});
|
142
|
-
if (globalResults?.hits) {
|
143
|
-
searchResults.push(...globalResults.hits);
|
144
|
-
}
|
145
|
-
}
|
146
|
-
catch (error) {
|
147
|
-
console.error("ā Error searching global index:", error);
|
148
|
-
}
|
149
|
-
}
|
150
|
-
// Search in user memories
|
151
|
-
if (options.userId &&
|
152
|
-
(!options.scope || options.scope === types_1.MemoryScope.USER)) {
|
153
|
-
const userIndex = this._getIndexName(types_1.MemoryScope.USER, options.userId);
|
154
|
-
const userResults = await this._makeRequest(`/indexes/${userIndex}/search`, {
|
120
|
+
console.log("\nš Searching in global index:", this.INDEX_PREFIX);
|
121
|
+
try {
|
122
|
+
const globalResults = await this._makeRequest(`/indexes/${this.INDEX_PREFIX}/search`, {
|
155
123
|
method: "POST",
|
156
124
|
body: JSON.stringify({ q: query }),
|
157
125
|
});
|
158
|
-
if (
|
159
|
-
searchResults.push(...
|
126
|
+
if (globalResults?.hits) {
|
127
|
+
searchResults.push(...globalResults.hits);
|
160
128
|
}
|
161
129
|
}
|
130
|
+
catch (error) {
|
131
|
+
console.error("ā Error searching global index:", error);
|
132
|
+
}
|
162
133
|
const totalResults = searchResults.length;
|
163
134
|
console.log(`\nš Found ${totalResults} total matches`);
|
164
135
|
// Process and filter results using cosine similarity
|
165
136
|
const results = searchResults
|
166
137
|
.flatMap((hit) => {
|
167
138
|
const chunkSimilarities = hit.chunks.map((chunk) => ({
|
168
|
-
createdAt: hit.createdAt,
|
169
|
-
data: hit.data,
|
170
|
-
purpose: hit.purpose,
|
171
139
|
query: hit.query,
|
172
|
-
|
140
|
+
data: hit.data,
|
173
141
|
similarityPercentage: ((0, ai_1.cosineSimilarity)(queryEmbedding, chunk.embedding) + 1) * 50,
|
142
|
+
createdAt: hit.createdAt,
|
174
143
|
}));
|
175
144
|
return chunkSimilarities.reduce((best, current) => current.similarityPercentage > best.similarityPercentage
|
176
145
|
? current
|
@@ -185,10 +154,6 @@ class PersistentMemory {
|
|
185
154
|
results.forEach((match, index) => {
|
186
155
|
console.log(`\n${index + 1}. Match Details:`);
|
187
156
|
console.log(` Query: ${match.query}`);
|
188
|
-
console.log(` Purpose: ${match.purpose}`);
|
189
|
-
console.log(` Similarity: ${match.similarityPercentage.toFixed(2)}%`);
|
190
|
-
console.log(` Content: "${match.chunk}"`);
|
191
|
-
console.log("ā".repeat(50));
|
192
157
|
});
|
193
158
|
}
|
194
159
|
else {
|
@@ -199,9 +164,8 @@ class PersistentMemory {
|
|
199
164
|
/**
|
200
165
|
* Delete memories for a given scope and user
|
201
166
|
*/
|
202
|
-
async deleteMemories(
|
203
|
-
|
204
|
-
return this._makeRequest(`/indexes/${indexName}`, {
|
167
|
+
async deleteMemories() {
|
168
|
+
return this._makeRequest(`/indexes/${this.INDEX_PREFIX}`, {
|
205
169
|
method: "DELETE",
|
206
170
|
});
|
207
171
|
}
|
@@ -0,0 +1,17 @@
|
|
1
|
+
import { Orchestrator } from "../llm/orchestrator";
|
2
|
+
import { ActionSchema, ScheduledAction, ScheduledActionEvents } from "../types";
|
3
|
+
import { ActionQueueManager } from "./queue";
|
4
|
+
export declare class ActionScheduler {
|
5
|
+
private actionQueueManager;
|
6
|
+
private orchestrator;
|
7
|
+
private scheduledActions;
|
8
|
+
private storage;
|
9
|
+
private events;
|
10
|
+
constructor(actionQueueManager: ActionQueueManager, orchestrator: Orchestrator, events?: ScheduledActionEvents);
|
11
|
+
scheduleAction(action: ActionSchema, scheduledTime: Date, userId: string, recurrence?: ScheduledAction["recurrence"]): Promise<string>;
|
12
|
+
private initializeScheduledActions;
|
13
|
+
private scheduleExecution;
|
14
|
+
private executeScheduledAction;
|
15
|
+
private calculateNextExecutionTime;
|
16
|
+
cancelScheduledAction(actionId: string): Promise<boolean>;
|
17
|
+
}
|