@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.
- package/.mocharc.json +1 -1
- package/README.md +311 -272
- package/dist/graph/controller.js +63 -0
- package/dist/graph/engine.js +563 -0
- package/dist/index.js +6 -6
- package/dist/memory/adapters/meilisearch/index.js +249 -0
- package/dist/memory/adapters/redis/index.js +96 -0
- package/dist/memory/index.js +9 -0
- package/dist/services/agenda.js +115 -0
- package/dist/services/embedding.js +40 -0
- package/dist/services/queue.js +99 -103
- package/dist/test/graph/controller.test.js +170 -0
- package/dist/test/graph/engine.test.js +465 -0
- package/dist/test/memory/adapters/meilisearch.test.js +250 -0
- package/dist/test/memory/adapters/redis.test.js +143 -0
- package/dist/test/memory/base.test.js +209 -0
- package/dist/test/services/agenda.test.js +230 -0
- package/dist/test/services/queue.test.js +258 -0
- package/dist/types/index.js +2 -0
- package/dist/utils/generate-object.js +32 -11
- package/dist/utils/inject-actions.js +2 -2
- package/dist/utils/queue-item-transformer.js +2 -2
- package/dist/utils/state-manager.js +20 -0
- package/graph/controller.ts +60 -0
- package/{services/workflow.ts ā graph/engine.ts} +331 -113
- package/index.ts +7 -7
- package/interfaces/index.ts +119 -0
- package/memory/adapters/meilisearch/index.ts +286 -0
- package/memory/adapters/redis/index.ts +103 -0
- package/memory/index.ts +22 -0
- package/package.json +7 -2
- package/services/agenda.ts +48 -43
- package/services/embedding.ts +26 -0
- package/services/queue.ts +2 -29
- package/test/.env.test +4 -0
- package/test/graph/controller.test.ts +186 -0
- package/test/graph/engine.test.ts +563 -0
- package/test/memory/adapters/meilisearch.test.ts +297 -0
- package/test/memory/adapters/redis.test.ts +160 -0
- package/test/memory/base.test.ts +229 -0
- package/test/services/agenda.test.ts +280 -0
- package/test/services/queue.test.ts +286 -44
- package/tsconfig.json +10 -10
- package/types/index.ts +270 -0
- package/utils/generate-object.js +111 -0
- package/utils/header-builder.js +34 -0
- package/utils/inject-actions.js +16 -0
- package/utils/queue-item-transformer.js +24 -0
- package/utils/queue-item-transformer.ts +8 -11
- package/utils/sanitize-results.js +60 -0
- package/utils/schema-generator.js +46 -0
- package/utils/state-manager.js +20 -0
- package/utils/state-manager.ts +17 -12
- package/.nvmrc +0 -1
- package/README.FR.md +0 -916
- package/agent/index.ts +0 -151
- package/agent/workflow/conditions.ts +0 -16
- package/agent/workflow/handlers/interpreter.handler.ts +0 -48
- package/agent/workflow/handlers/memory.handler.ts +0 -106
- package/agent/workflow/handlers/orchestrator.handler.ts +0 -23
- package/agent/workflow/handlers/queue.handler.ts +0 -34
- package/agent/workflow/handlers/scheduler.handler.ts +0 -61
- package/agent/workflow/index.ts +0 -62
- package/dist/agent/index.d.ts +0 -38
- package/dist/agent/index.js +0 -143
- package/dist/agent/tools/get-rss.d.ts +0 -16
- package/dist/agent/tools/get-rss.js +0 -62
- package/dist/bull.d.ts +0 -1
- package/dist/bull.js +0 -9
- package/dist/examples/index.d.ts +0 -2
- package/dist/examples/index.js +0 -89
- package/dist/index.d.ts +0 -7
- package/dist/llm/interpreter/context.d.ts +0 -15
- package/dist/llm/interpreter/context.js +0 -89
- package/dist/llm/interpreter/index.d.ts +0 -21
- package/dist/llm/interpreter/index.js +0 -87
- package/dist/llm/memory-manager/context.d.ts +0 -2
- package/dist/llm/memory-manager/context.js +0 -22
- package/dist/llm/memory-manager/index.d.ts +0 -17
- package/dist/llm/memory-manager/index.js +0 -107
- package/dist/llm/orchestrator/context.d.ts +0 -2
- package/dist/llm/orchestrator/context.js +0 -23
- package/dist/llm/orchestrator/index.d.ts +0 -44
- package/dist/llm/orchestrator/index.js +0 -139
- package/dist/llm/orchestrator/types.d.ts +0 -12
- package/dist/memory/cache.d.ts +0 -22
- package/dist/memory/cache.js +0 -165
- package/dist/memory/persistent.d.ts +0 -57
- package/dist/memory/persistent.js +0 -189
- package/dist/services/queue.d.ts +0 -13
- package/dist/services/redis-cache.d.ts +0 -37
- package/dist/services/redis-cache.js +0 -93
- package/dist/services/scheduler.d.ts +0 -40
- package/dist/services/scheduler.js +0 -99
- package/dist/services/telegram-monitor.d.ts +0 -0
- package/dist/services/telegram-monitor.js +0 -118
- package/dist/t.d.ts +0 -46
- package/dist/t.js +0 -102
- package/dist/test.d.ts +0 -0
- package/dist/test.js +0 -438
- package/dist/types.d.ts +0 -258
- package/dist/types.js +0 -22
- package/dist/utils/generate-object.d.ts +0 -12
- package/dist/utils/header-builder.d.ts +0 -11
- package/dist/utils/inject-actions.d.ts +0 -2
- package/dist/utils/queue-item-transformer.d.ts +0 -7
- package/dist/utils/sanitize-results.d.ts +0 -17
- package/dist/utils/schema-generator.d.ts +0 -16
- package/examples/actions/get-rss.ts +0 -71
- package/examples/index.ts +0 -98
- package/index.html +0 -42
- package/llm/dynamic-condition/example.ts +0 -36
- package/llm/dynamic-condition/index.ts +0 -108
- package/llm/interpreter/context.ts +0 -94
- package/llm/interpreter/index.ts +0 -140
- package/llm/memory-manager/context.ts +0 -19
- package/llm/memory-manager/index.ts +0 -115
- package/llm/orchestrator/context.ts +0 -19
- package/llm/orchestrator/index.ts +0 -192
- package/llm/orchestrator/types.ts +0 -14
- package/memory/cache.ts +0 -221
- package/memory/persistent.ts +0 -265
- package/script.js +0 -167
- package/services/cache.ts +0 -298
- package/services/telegram-monitor.ts +0 -138
- package/t.py +0 -79
- package/t.ts +0 -25
- package/test/llm/orchestrator.test.ts +0 -47
- package/test/llm/synthesizer.test.ts +0 -31
- package/types.ts +0 -367
- /package/dist/{llm/orchestrator/types.js ā interfaces/index.js} +0 -0
@@ -1,139 +0,0 @@
|
|
1
|
-
"use strict";
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
3
|
-
exports.AgentRuntime = void 0;
|
4
|
-
const zod_1 = require("zod");
|
5
|
-
const queue_1 = require("../../services/queue");
|
6
|
-
const redis_cache_1 = require("../../services/redis-cache");
|
7
|
-
const scheduler_1 = require("../../services/scheduler");
|
8
|
-
const types_1 = require("../../types");
|
9
|
-
const generate_object_1 = require("../../utils/generate-object");
|
10
|
-
const header_builder_1 = require("../../utils/header-builder");
|
11
|
-
const inject_actions_1 = require("../../utils/inject-actions");
|
12
|
-
const context_1 = require("./context");
|
13
|
-
class AgentRuntime {
|
14
|
-
constructor(model, tools, interpreters, redisConfig, memory, callbacks) {
|
15
|
-
this.model = model;
|
16
|
-
this.tools = tools;
|
17
|
-
this.interpreters = interpreters;
|
18
|
-
this.queueManager = new queue_1.ActionQueueManager(tools, callbacks);
|
19
|
-
this.memory = memory;
|
20
|
-
this.cache = new redis_cache_1.RedisCache(redisConfig);
|
21
|
-
this.scheduler = new scheduler_1.TaskScheduler(this, this.cache);
|
22
|
-
}
|
23
|
-
async buildContext(state) {
|
24
|
-
console.log("š§ Building context with RAG and CAG...");
|
25
|
-
const context = header_builder_1.LLMHeaderBuilder.create();
|
26
|
-
// Add orchestrator instructions
|
27
|
-
context.addHeader("ROLE", context_1.orchestratorInstructions.role);
|
28
|
-
context.addHeader("LANGUAGE", context_1.orchestratorInstructions.language);
|
29
|
-
context.addHeader("IMPORTANT", context_1.orchestratorInstructions.guidelines.important);
|
30
|
-
context.addHeader("WARNINGS", context_1.orchestratorInstructions.guidelines.warnings);
|
31
|
-
// Add tools to context
|
32
|
-
context.addHeader("TOOLS", (0, inject_actions_1.injectActions)(this.tools));
|
33
|
-
// Add previous actions if any
|
34
|
-
if (state.previousActions?.length) {
|
35
|
-
context.addHeader("PREVIOUS_ACTIONS", JSON.stringify(state.previousActions));
|
36
|
-
}
|
37
|
-
// Get recent similar actions (CAG)
|
38
|
-
if (this.memory?.cache) {
|
39
|
-
const cacheMemories = await this.memory.cache.findSimilarActions(state.currentContext, {
|
40
|
-
similarityThreshold: 80,
|
41
|
-
maxResults: 3,
|
42
|
-
scope: types_1.MemoryScope.GLOBAL,
|
43
|
-
});
|
44
|
-
if (cacheMemories.length > 0) {
|
45
|
-
context.addHeader("RECENT_ACTIONS", JSON.stringify(cacheMemories));
|
46
|
-
}
|
47
|
-
}
|
48
|
-
// Get relevant knowledge (RAG)
|
49
|
-
if (this.memory?.persistent) {
|
50
|
-
const persistentMemory = await this.memory.persistent.findRelevantDocuments(state.currentContext, {
|
51
|
-
similarityThreshold: 80,
|
52
|
-
});
|
53
|
-
if (persistentMemory.length > 0) {
|
54
|
-
context.addHeader("RELEVANT_KNOWLEDGE", JSON.stringify(persistentMemory));
|
55
|
-
}
|
56
|
-
}
|
57
|
-
// Add available interpreters
|
58
|
-
context.addHeader("AVAILABLE_INTERPRETERS", JSON.stringify(this.interpreters.map((i) => i.name)));
|
59
|
-
console.log("Context built with memories", context.toString());
|
60
|
-
return context.toString();
|
61
|
-
}
|
62
|
-
async process(state) {
|
63
|
-
console.log("š Processing state:");
|
64
|
-
console.dir(state, { depth: null });
|
65
|
-
if (state.previousActions?.length) {
|
66
|
-
console.log("š Previous actions:", state.previousActions
|
67
|
-
.map((a) => (typeof a === "string" ? a : a.name))
|
68
|
-
.join(", "));
|
69
|
-
}
|
70
|
-
const context = await this.buildContext(state);
|
71
|
-
console.log("\nš§ Generating response from LLM...");
|
72
|
-
const response = await (0, generate_object_1.generateObject)({
|
73
|
-
model: this.model,
|
74
|
-
schema: zod_1.z.object({
|
75
|
-
shouldContinue: zod_1.z.boolean(),
|
76
|
-
actions: zod_1.z.array(zod_1.z.object({
|
77
|
-
name: zod_1.z.string(),
|
78
|
-
parameters: zod_1.z.array(zod_1.z.object({
|
79
|
-
name: zod_1.z.string(),
|
80
|
-
value: zod_1.z.any(),
|
81
|
-
})),
|
82
|
-
scheduler: zod_1.z
|
83
|
-
.object({
|
84
|
-
isScheduled: zod_1.z.boolean(),
|
85
|
-
cronExpression: zod_1.z.string().optional(),
|
86
|
-
reason: zod_1.z.string().optional(),
|
87
|
-
})
|
88
|
-
.optional(),
|
89
|
-
})),
|
90
|
-
socialResponse: zod_1.z
|
91
|
-
.object({
|
92
|
-
shouldRespond: zod_1.z.boolean(),
|
93
|
-
response: zod_1.z.string().optional(),
|
94
|
-
isPartialResponse: zod_1.z.boolean().optional(),
|
95
|
-
})
|
96
|
-
.optional(),
|
97
|
-
interpreter: zod_1.z.string().optional(),
|
98
|
-
}),
|
99
|
-
prompt: state.currentContext,
|
100
|
-
system: context.toString(),
|
101
|
-
temperature: 0,
|
102
|
-
});
|
103
|
-
console.log("š Orchestrator response:");
|
104
|
-
console.dir(response.object, { depth: null });
|
105
|
-
// Force shouldContinue to false if no actions are planned
|
106
|
-
if (response.object.actions.length === 0) {
|
107
|
-
response.object.shouldContinue = false;
|
108
|
-
console.log("ā ļø No actions planned, forcing shouldContinue to false");
|
109
|
-
}
|
110
|
-
// Handle social interactions and actions in a single block
|
111
|
-
if (response.object.socialResponse?.shouldRespond) {
|
112
|
-
console.log("\nš¬ Processing social response");
|
113
|
-
if (response.object.socialResponse.response) {
|
114
|
-
console.log("š¢ Response:", response.object.socialResponse.response);
|
115
|
-
// Ensure all parameters have a value property
|
116
|
-
}
|
117
|
-
}
|
118
|
-
// Handle scheduled actions
|
119
|
-
for (const action of response.object.actions) {
|
120
|
-
if (action.scheduler?.isScheduled) {
|
121
|
-
await this.scheduler.scheduleRequest({
|
122
|
-
originalRequest: state.currentContext,
|
123
|
-
cronExpression: action.scheduler.cronExpression,
|
124
|
-
});
|
125
|
-
}
|
126
|
-
}
|
127
|
-
// Store actions in Redis cache
|
128
|
-
if (response.object.actions.length > 0) {
|
129
|
-
const requestId = crypto.randomUUID();
|
130
|
-
await this.cache.storePreviousActions(requestId, response.object.actions);
|
131
|
-
}
|
132
|
-
// Store message in recent messages
|
133
|
-
await this.cache.storeRecentMessage(state.currentContext, {
|
134
|
-
socialResponse: response.object.socialResponse,
|
135
|
-
});
|
136
|
-
return response.object;
|
137
|
-
}
|
138
|
-
}
|
139
|
-
exports.AgentRuntime = AgentRuntime;
|
@@ -1,12 +0,0 @@
|
|
1
|
-
import { QueueResult } from "../../types";
|
2
|
-
export interface State {
|
3
|
-
currentContext: string;
|
4
|
-
previousActions: (string | QueueResult)[];
|
5
|
-
reward?: number;
|
6
|
-
userRequest?: string;
|
7
|
-
results?: string;
|
8
|
-
}
|
9
|
-
export interface Action {
|
10
|
-
name: string;
|
11
|
-
parameters: Record<string, any>;
|
12
|
-
}
|
package/dist/memory/cache.d.ts
DELETED
@@ -1,22 +0,0 @@
|
|
1
|
-
import { CacheMemoryOptions, CacheMemoryType, CreateMemoryInput, MatchOptions, MemoryScope } from "../types";
|
2
|
-
export declare class CacheMemory {
|
3
|
-
private redis;
|
4
|
-
private readonly CACHE_PREFIX;
|
5
|
-
private readonly CACHE_TTL;
|
6
|
-
private readonly embeddingModel;
|
7
|
-
constructor(options: CacheMemoryOptions);
|
8
|
-
private initRedis;
|
9
|
-
private storeMemory;
|
10
|
-
findSimilarActions(query: string, options?: MatchOptions & {
|
11
|
-
userId?: string;
|
12
|
-
scope?: MemoryScope;
|
13
|
-
}): Promise<{
|
14
|
-
data: any;
|
15
|
-
query: string;
|
16
|
-
createdAt: Date;
|
17
|
-
}[]>;
|
18
|
-
getAllMemories(): Promise<CacheMemoryType[]>;
|
19
|
-
private getMemoriesFromKeys;
|
20
|
-
createMemory(input: CreateMemoryInput): Promise<CacheMemoryType | undefined>;
|
21
|
-
private createSingleMemory;
|
22
|
-
}
|
package/dist/memory/cache.js
DELETED
@@ -1,165 +0,0 @@
|
|
1
|
-
"use strict";
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
3
|
-
exports.CacheMemory = void 0;
|
4
|
-
const openai_1 = require("@ai-sdk/openai");
|
5
|
-
const ai_1 = require("ai");
|
6
|
-
const redis_1 = require("redis");
|
7
|
-
const types_1 = require("../types");
|
8
|
-
class CacheMemory {
|
9
|
-
constructor(options) {
|
10
|
-
this.embeddingModel = options.embeddingModel;
|
11
|
-
const ttlInHours = options.cacheTTL ?? 1;
|
12
|
-
this.CACHE_TTL = ttlInHours * 60 * 60;
|
13
|
-
this.CACHE_PREFIX = options.cachePrefix ?? "memory:";
|
14
|
-
this.redis = (0, redis_1.createClient)({
|
15
|
-
url: options.redisUrl || process.env.REDIS_URL,
|
16
|
-
socket: {
|
17
|
-
tls: true,
|
18
|
-
rejectUnauthorized: true,
|
19
|
-
},
|
20
|
-
});
|
21
|
-
this.initRedis();
|
22
|
-
}
|
23
|
-
async initRedis() {
|
24
|
-
this.redis.on("error", (err) => {
|
25
|
-
console.error("ā Redis Client Error:", err);
|
26
|
-
});
|
27
|
-
try {
|
28
|
-
await this.redis.connect();
|
29
|
-
console.log("ā
Successfully connected to Redis");
|
30
|
-
}
|
31
|
-
catch (error) {
|
32
|
-
console.error("ā Failed to connect to Redis:", error);
|
33
|
-
}
|
34
|
-
}
|
35
|
-
async storeMemory(memory, ttl) {
|
36
|
-
const prefix = this.CACHE_PREFIX;
|
37
|
-
const key = `${prefix}${memory.id}`;
|
38
|
-
const result = await this.redis.set(key, JSON.stringify(memory), {
|
39
|
-
EX: ttl || this.CACHE_TTL,
|
40
|
-
});
|
41
|
-
console.log("š¾ Cache memory created:", result);
|
42
|
-
}
|
43
|
-
async findSimilarActions(query, options = {}) {
|
44
|
-
console.log("\nš Searching in cache");
|
45
|
-
console.log("Query:", query);
|
46
|
-
console.log("Options:", JSON.stringify(options, null, 2));
|
47
|
-
const { embedding } = await (0, ai_1.embed)({
|
48
|
-
model: openai_1.openai.embedding("text-embedding-3-small"),
|
49
|
-
value: query,
|
50
|
-
});
|
51
|
-
const memories = await this.getAllMemories();
|
52
|
-
console.log(`\nš Found ${memories.length} cached queries to compare`);
|
53
|
-
const matches = memories
|
54
|
-
.map((memory) => {
|
55
|
-
const similarity = (0, ai_1.cosineSimilarity)(embedding, memory.embedding);
|
56
|
-
const similarityPercentage = (similarity + 1) * 50;
|
57
|
-
return {
|
58
|
-
data: memory.data,
|
59
|
-
query: memory.query,
|
60
|
-
similarityPercentage,
|
61
|
-
createdAt: memory.createdAt,
|
62
|
-
};
|
63
|
-
})
|
64
|
-
.filter((match) => match.similarityPercentage >= (options.similarityThreshold ?? 70))
|
65
|
-
.sort((a, b) => b.similarityPercentage - a.similarityPercentage);
|
66
|
-
const results = options.maxResults
|
67
|
-
? matches.slice(0, options.maxResults)
|
68
|
-
: matches;
|
69
|
-
if (results.length > 0) {
|
70
|
-
console.log("\n⨠Similar queries found:");
|
71
|
-
console.log("ā".repeat(50));
|
72
|
-
results.forEach((match, index) => {
|
73
|
-
console.log(`\n${index + 1}. Match Details:`);
|
74
|
-
console.log(` Query: ${match.query}`);
|
75
|
-
console.log(` Data: ${JSON.stringify(match.data)}`);
|
76
|
-
console.log(` Similarity: ${match.similarityPercentage.toFixed(2)}%`);
|
77
|
-
console.log("ā".repeat(50));
|
78
|
-
});
|
79
|
-
}
|
80
|
-
else {
|
81
|
-
console.log("\nā No similar queries found in cache");
|
82
|
-
}
|
83
|
-
return results.map((match) => {
|
84
|
-
return {
|
85
|
-
data: match.data,
|
86
|
-
query: match.query,
|
87
|
-
createdAt: match.createdAt,
|
88
|
-
};
|
89
|
-
});
|
90
|
-
}
|
91
|
-
async getAllMemories() {
|
92
|
-
const keys = await this.redis.keys(`${this.CACHE_PREFIX}*`);
|
93
|
-
const memories = await this.getMemoriesFromKeys(keys);
|
94
|
-
return memories;
|
95
|
-
}
|
96
|
-
async getMemoriesFromKeys(keys) {
|
97
|
-
const memories = [];
|
98
|
-
for (const key of keys) {
|
99
|
-
const data = await this.redis.get(key);
|
100
|
-
if (data) {
|
101
|
-
memories.push(JSON.parse(data));
|
102
|
-
}
|
103
|
-
}
|
104
|
-
return memories;
|
105
|
-
}
|
106
|
-
async createMemory(input) {
|
107
|
-
console.log("\nš Processing new memory creation");
|
108
|
-
console.log("Content:", input.query);
|
109
|
-
console.log("TTL:", input.ttl ? `${input.ttl} seconds` : "default");
|
110
|
-
const existingPattern = await this.findSimilarActions(input.query, {
|
111
|
-
similarityThreshold: 95,
|
112
|
-
userId: input.userId,
|
113
|
-
scope: input.scope,
|
114
|
-
});
|
115
|
-
if (existingPattern.length > 0) {
|
116
|
-
console.log("\nš Similar cache memory already exists");
|
117
|
-
console.log("ā".repeat(50));
|
118
|
-
existingPattern.forEach((match, index) => {
|
119
|
-
console.log(`\n${index + 1}. Existing Match:`);
|
120
|
-
console.log(` Query: ${match.query}`);
|
121
|
-
console.log(` Data: ${JSON.stringify(match.data)}`);
|
122
|
-
console.log(` Created At: ${match.createdAt}`);
|
123
|
-
});
|
124
|
-
console.log("\nāļø Skipping creation of new memory");
|
125
|
-
return;
|
126
|
-
}
|
127
|
-
console.log("\nš No similar memory found - creating new one");
|
128
|
-
const memory = await this.createSingleMemory({
|
129
|
-
id: crypto.randomUUID(),
|
130
|
-
query: input.query,
|
131
|
-
data: input.data,
|
132
|
-
userId: input.userId,
|
133
|
-
scope: input.scope,
|
134
|
-
ttl: input.ttl,
|
135
|
-
});
|
136
|
-
return memory;
|
137
|
-
}
|
138
|
-
async createSingleMemory(params) {
|
139
|
-
console.log("\nšļø Creating new cache memory");
|
140
|
-
console.log("ID:", params.id);
|
141
|
-
console.log("Content:", params.query);
|
142
|
-
console.log("\nš§® Generating embedding...");
|
143
|
-
const { embedding } = await (0, ai_1.embed)({
|
144
|
-
model: this.embeddingModel,
|
145
|
-
value: params.query,
|
146
|
-
});
|
147
|
-
console.log("ā
Embedding generated successfully");
|
148
|
-
const memory = {
|
149
|
-
id: params.id,
|
150
|
-
data: params.data,
|
151
|
-
query: params.query,
|
152
|
-
embedding,
|
153
|
-
userId: params.userId,
|
154
|
-
scope: params.scope || (params.userId ? types_1.MemoryScope.USER : types_1.MemoryScope.GLOBAL),
|
155
|
-
createdAt: new Date(),
|
156
|
-
};
|
157
|
-
await this.storeMemory(memory, params.ttl);
|
158
|
-
console.log("ā
Short-term memory created and stored successfully", {
|
159
|
-
...memory,
|
160
|
-
ttl: params.ttl || this.CACHE_TTL,
|
161
|
-
});
|
162
|
-
return memory;
|
163
|
-
}
|
164
|
-
}
|
165
|
-
exports.CacheMemory = CacheMemory;
|
@@ -1,57 +0,0 @@
|
|
1
|
-
import { EmbeddingModel } from "ai";
|
2
|
-
import { LongTermMemory, MemoryScope } from "../types";
|
3
|
-
interface SearchOptions {
|
4
|
-
scope?: MemoryScope;
|
5
|
-
userId?: string;
|
6
|
-
maxResults?: number;
|
7
|
-
similarityThreshold?: number;
|
8
|
-
}
|
9
|
-
interface ProcessedChunk {
|
10
|
-
content: string;
|
11
|
-
embedding: number[];
|
12
|
-
}
|
13
|
-
/**
|
14
|
-
* Handles persistent memory storage using Meilisearch API
|
15
|
-
*/
|
16
|
-
export declare class PersistentMemory {
|
17
|
-
private readonly host;
|
18
|
-
private readonly apiKey;
|
19
|
-
private readonly INDEX_PREFIX;
|
20
|
-
private readonly embeddingModel;
|
21
|
-
constructor(options: {
|
22
|
-
host: string;
|
23
|
-
apiKey: string;
|
24
|
-
indexPrefix?: string;
|
25
|
-
embeddingModel: EmbeddingModel<string>;
|
26
|
-
});
|
27
|
-
/**
|
28
|
-
* Initialize indexes
|
29
|
-
*/
|
30
|
-
init(): Promise<void>;
|
31
|
-
/**
|
32
|
-
* Make API request to Meilisearch
|
33
|
-
*/
|
34
|
-
private _makeRequest;
|
35
|
-
/**
|
36
|
-
* Get or create an index with proper settings
|
37
|
-
*/
|
38
|
-
private _getOrCreateIndex;
|
39
|
-
processContent(content: string): Promise<ProcessedChunk[]>;
|
40
|
-
/**
|
41
|
-
* Store a memory in the database
|
42
|
-
*/
|
43
|
-
createMemory(memory: LongTermMemory): Promise<unknown>;
|
44
|
-
/**
|
45
|
-
* Find best matching memories
|
46
|
-
*/
|
47
|
-
findRelevantDocuments(query: string, options?: SearchOptions): Promise<{
|
48
|
-
query: string;
|
49
|
-
data: any;
|
50
|
-
createdAt: string;
|
51
|
-
}[]>;
|
52
|
-
/**
|
53
|
-
* Delete memories for a given scope and user
|
54
|
-
*/
|
55
|
-
deleteMemories(): Promise<unknown>;
|
56
|
-
}
|
57
|
-
export {};
|
@@ -1,189 +0,0 @@
|
|
1
|
-
"use strict";
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
3
|
-
exports.PersistentMemory = void 0;
|
4
|
-
const ai_1 = require("ai");
|
5
|
-
const text_splitter_1 = require("langchain/text_splitter");
|
6
|
-
/**
|
7
|
-
* Handles persistent memory storage using Meilisearch API
|
8
|
-
*/
|
9
|
-
class PersistentMemory {
|
10
|
-
constructor(options) {
|
11
|
-
this.host = options.host;
|
12
|
-
this.apiKey = options.apiKey;
|
13
|
-
this.INDEX_PREFIX = options.indexPrefix || "memory";
|
14
|
-
this.embeddingModel = options.embeddingModel;
|
15
|
-
}
|
16
|
-
/**
|
17
|
-
* Initialize indexes
|
18
|
-
*/
|
19
|
-
async init() {
|
20
|
-
try {
|
21
|
-
// Create or get main index
|
22
|
-
await this._getOrCreateIndex(this.INDEX_PREFIX);
|
23
|
-
console.log(`ā
Index '${this.INDEX_PREFIX}' initialized successfully`);
|
24
|
-
}
|
25
|
-
catch (error) {
|
26
|
-
console.error(`ā Failed to initialize index: ${error}`);
|
27
|
-
throw error;
|
28
|
-
}
|
29
|
-
}
|
30
|
-
/**
|
31
|
-
* Make API request to Meilisearch
|
32
|
-
*/
|
33
|
-
async _makeRequest(path, options = {}) {
|
34
|
-
const url = `${this.host}${path}`;
|
35
|
-
console.log("š Making request to Meilisearch:", url);
|
36
|
-
const response = await fetch(url, {
|
37
|
-
...options,
|
38
|
-
headers: {
|
39
|
-
"Content-Type": "application/json",
|
40
|
-
Authorization: `Bearer ${this.apiKey}`,
|
41
|
-
...options.headers,
|
42
|
-
},
|
43
|
-
});
|
44
|
-
if (!response.ok) {
|
45
|
-
console.log({ response });
|
46
|
-
throw new Error(`Meilisearch API error: ${response.statusText}`);
|
47
|
-
}
|
48
|
-
return response.json();
|
49
|
-
}
|
50
|
-
/**
|
51
|
-
* Get or create an index with proper settings
|
52
|
-
*/
|
53
|
-
async _getOrCreateIndex(indexName) {
|
54
|
-
try {
|
55
|
-
// Check if index exists first
|
56
|
-
const indexExists = await this._makeRequest(`/indexes/${indexName}`, {
|
57
|
-
method: "GET",
|
58
|
-
}).catch(() => false);
|
59
|
-
if (!indexExists) {
|
60
|
-
console.log(`Creating new index: ${indexName}`);
|
61
|
-
await this._makeRequest("/indexes", {
|
62
|
-
method: "POST",
|
63
|
-
body: JSON.stringify({
|
64
|
-
uid: indexName,
|
65
|
-
primaryKey: "id",
|
66
|
-
}),
|
67
|
-
});
|
68
|
-
}
|
69
|
-
// Update index settings
|
70
|
-
const settings = {
|
71
|
-
searchableAttributes: ["query", "purpose", "chunks.content"],
|
72
|
-
sortableAttributes: ["createdAt"],
|
73
|
-
};
|
74
|
-
await this._makeRequest(`/indexes/${indexName}/settings`, {
|
75
|
-
method: "PATCH",
|
76
|
-
body: JSON.stringify(settings),
|
77
|
-
});
|
78
|
-
console.log(`Index ${indexName} configured successfully`);
|
79
|
-
}
|
80
|
-
catch (error) {
|
81
|
-
console.error(`Failed to configure index ${indexName}:`, error);
|
82
|
-
throw error;
|
83
|
-
}
|
84
|
-
}
|
85
|
-
async processContent(content) {
|
86
|
-
// Split content into chunks
|
87
|
-
const textSplitter = new text_splitter_1.RecursiveCharacterTextSplitter({
|
88
|
-
chunkSize: 1000,
|
89
|
-
});
|
90
|
-
const chunks = await textSplitter.createDocuments([content]);
|
91
|
-
// Generate embeddings for all chunks
|
92
|
-
const { embeddings } = await (0, ai_1.embedMany)({
|
93
|
-
model: this.embeddingModel,
|
94
|
-
values: chunks.map((chunk) => chunk.pageContent),
|
95
|
-
});
|
96
|
-
// Create processed chunks with embeddings
|
97
|
-
return chunks.map((chunk, i) => ({
|
98
|
-
content: chunk.pageContent,
|
99
|
-
embedding: embeddings[i],
|
100
|
-
}));
|
101
|
-
}
|
102
|
-
/**
|
103
|
-
* Store a memory in the database
|
104
|
-
*/
|
105
|
-
async createMemory(memory) {
|
106
|
-
try {
|
107
|
-
console.log(`š Creating memory in index: ${this.INDEX_PREFIX}`);
|
108
|
-
// Process content into chunks with embeddings
|
109
|
-
const chunks = await this.processContent(memory.data);
|
110
|
-
// Generate unique ID if not provided
|
111
|
-
const id = memory.id || crypto.randomUUID();
|
112
|
-
const document = {
|
113
|
-
...memory,
|
114
|
-
chunks,
|
115
|
-
createdAt: memory.createdAt.toISOString(),
|
116
|
-
};
|
117
|
-
const response = await this._makeRequest(`/indexes/${this.INDEX_PREFIX}/documents`, {
|
118
|
-
method: "POST",
|
119
|
-
body: JSON.stringify([document]),
|
120
|
-
});
|
121
|
-
console.log("ā
Memory created successfully", { id });
|
122
|
-
return response;
|
123
|
-
}
|
124
|
-
catch (error) {
|
125
|
-
console.error("ā Failed to create memory:", error);
|
126
|
-
throw error;
|
127
|
-
}
|
128
|
-
}
|
129
|
-
/**
|
130
|
-
* Find best matching memories
|
131
|
-
*/
|
132
|
-
async findRelevantDocuments(query, options = {}) {
|
133
|
-
console.log(`\nš Searching in index: ${this.INDEX_PREFIX}`);
|
134
|
-
console.log("Query:", query);
|
135
|
-
try {
|
136
|
-
// Generate embedding for the query
|
137
|
-
const { embedding: queryEmbedding } = await (0, ai_1.embed)({
|
138
|
-
model: this.embeddingModel,
|
139
|
-
value: query,
|
140
|
-
});
|
141
|
-
// Search in the index
|
142
|
-
const searchResults = await this._makeRequest(`/indexes/${this.INDEX_PREFIX}/search`, {
|
143
|
-
method: "POST",
|
144
|
-
body: JSON.stringify({
|
145
|
-
q: query,
|
146
|
-
limit: options.maxResults || 10,
|
147
|
-
}),
|
148
|
-
});
|
149
|
-
if (!searchResults?.hits?.length) {
|
150
|
-
console.log("ā No matches found");
|
151
|
-
return [];
|
152
|
-
}
|
153
|
-
// Process and filter results using cosine similarity
|
154
|
-
const results = searchResults.hits
|
155
|
-
.flatMap((hit) => {
|
156
|
-
const chunkSimilarities = hit.chunks.map((chunk) => ({
|
157
|
-
query: hit.query,
|
158
|
-
data: hit.data,
|
159
|
-
similarityPercentage: ((0, ai_1.cosineSimilarity)(queryEmbedding, chunk.embedding) + 1) * 50,
|
160
|
-
createdAt: hit.createdAt,
|
161
|
-
}));
|
162
|
-
return chunkSimilarities.reduce((best, current) => current.similarityPercentage > best.similarityPercentage
|
163
|
-
? current
|
164
|
-
: best, chunkSimilarities[0]);
|
165
|
-
})
|
166
|
-
.filter((match) => match.similarityPercentage >= (options.similarityThreshold || 70))
|
167
|
-
.sort((a, b) => b.similarityPercentage - a.similarityPercentage);
|
168
|
-
console.log(`⨠Found ${results.length} relevant matches`);
|
169
|
-
return results.map((result) => ({
|
170
|
-
query: result.query,
|
171
|
-
data: result.data,
|
172
|
-
createdAt: result.createdAt,
|
173
|
-
}));
|
174
|
-
}
|
175
|
-
catch (error) {
|
176
|
-
console.error("ā Search failed:", error);
|
177
|
-
return [];
|
178
|
-
}
|
179
|
-
}
|
180
|
-
/**
|
181
|
-
* Delete memories for a given scope and user
|
182
|
-
*/
|
183
|
-
async deleteMemories() {
|
184
|
-
return this._makeRequest(`/indexes/${this.INDEX_PREFIX}`, {
|
185
|
-
method: "DELETE",
|
186
|
-
});
|
187
|
-
}
|
188
|
-
}
|
189
|
-
exports.PersistentMemory = PersistentMemory;
|
package/dist/services/queue.d.ts
DELETED
@@ -1,13 +0,0 @@
|
|
1
|
-
import { ActionSchema, QueueCallbacks, QueueItem, QueueResult } from "../types";
|
2
|
-
export declare class ActionQueueManager {
|
3
|
-
private queue;
|
4
|
-
private results;
|
5
|
-
private callbacks;
|
6
|
-
private actions;
|
7
|
-
private isProcessing;
|
8
|
-
constructor(actions: ActionSchema[], callbacks?: QueueCallbacks);
|
9
|
-
addToQueue(actions: QueueItem | QueueItem[]): void;
|
10
|
-
processQueue(): Promise<QueueResult[] | undefined>;
|
11
|
-
private formatArguments;
|
12
|
-
private executeAction;
|
13
|
-
}
|
@@ -1,37 +0,0 @@
|
|
1
|
-
export interface CacheConfig {
|
2
|
-
host: string;
|
3
|
-
port: number;
|
4
|
-
password?: string;
|
5
|
-
ttl?: number;
|
6
|
-
cleanupInterval?: string;
|
7
|
-
}
|
8
|
-
export declare class RedisCache {
|
9
|
-
private redis;
|
10
|
-
private readonly defaultTTL;
|
11
|
-
private readonly cleanupJob;
|
12
|
-
constructor(config: CacheConfig);
|
13
|
-
/**
|
14
|
-
* Store previous actions for a specific request
|
15
|
-
*/
|
16
|
-
storePreviousActions(requestId: string, actions: any[]): Promise<void>;
|
17
|
-
/**
|
18
|
-
* Get previous actions for a specific request
|
19
|
-
*/
|
20
|
-
getPreviousActions(requestId: string): Promise<any[]>;
|
21
|
-
/**
|
22
|
-
* Store a recent message
|
23
|
-
*/
|
24
|
-
storeRecentMessage(message: string, metadata?: Record<string, any>): Promise<void>;
|
25
|
-
/**
|
26
|
-
* Get recent messages
|
27
|
-
*/
|
28
|
-
getRecentMessages(limit?: number): Promise<any[]>;
|
29
|
-
/**
|
30
|
-
* Cleanup expired keys
|
31
|
-
*/
|
32
|
-
private cleanup;
|
33
|
-
/**
|
34
|
-
* Stop the cleanup job and close Redis connection
|
35
|
-
*/
|
36
|
-
close(): Promise<void>;
|
37
|
-
}
|