@ai.ntellect/core 0.4.1 → 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 (125) 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/graph/engine.ts +709 -0
  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 +9 -2
  32. package/services/agenda.ts +118 -0
  33. package/services/embedding.ts +26 -0
  34. package/services/queue.ts +5 -32
  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 -9
  44. package/types/index.ts +270 -0
  45. package/utils/generate-object.js +111 -0
  46. package/utils/generate-object.ts +24 -12
  47. package/utils/header-builder.js +34 -0
  48. package/utils/inject-actions.js +16 -0
  49. package/utils/inject-actions.ts +3 -3
  50. package/utils/queue-item-transformer.js +24 -0
  51. package/utils/queue-item-transformer.ts +8 -11
  52. package/utils/sanitize-results.js +60 -0
  53. package/utils/schema-generator.js +46 -0
  54. package/utils/state-manager.js +20 -0
  55. package/utils/state-manager.ts +30 -0
  56. package/.nvmrc +0 -1
  57. package/README.FR.md +0 -365
  58. package/agent/index.ts +0 -244
  59. package/agent/tools/get-rss.ts +0 -64
  60. package/bull.ts +0 -5
  61. package/dist/agent/index.d.ts +0 -38
  62. package/dist/agent/index.js +0 -143
  63. package/dist/agent/tools/get-rss.d.ts +0 -16
  64. package/dist/agent/tools/get-rss.js +0 -62
  65. package/dist/bull.d.ts +0 -1
  66. package/dist/bull.js +0 -9
  67. package/dist/examples/index.d.ts +0 -2
  68. package/dist/examples/index.js +0 -89
  69. package/dist/index.d.ts +0 -7
  70. package/dist/llm/interpreter/context.d.ts +0 -15
  71. package/dist/llm/interpreter/context.js +0 -89
  72. package/dist/llm/interpreter/index.d.ts +0 -21
  73. package/dist/llm/interpreter/index.js +0 -87
  74. package/dist/llm/memory-manager/context.d.ts +0 -2
  75. package/dist/llm/memory-manager/context.js +0 -22
  76. package/dist/llm/memory-manager/index.d.ts +0 -17
  77. package/dist/llm/memory-manager/index.js +0 -107
  78. package/dist/llm/orchestrator/context.d.ts +0 -2
  79. package/dist/llm/orchestrator/context.js +0 -23
  80. package/dist/llm/orchestrator/index.d.ts +0 -44
  81. package/dist/llm/orchestrator/index.js +0 -139
  82. package/dist/llm/orchestrator/types.d.ts +0 -12
  83. package/dist/memory/cache.d.ts +0 -22
  84. package/dist/memory/cache.js +0 -165
  85. package/dist/memory/persistent.d.ts +0 -57
  86. package/dist/memory/persistent.js +0 -189
  87. package/dist/services/queue.d.ts +0 -13
  88. package/dist/services/redis-cache.d.ts +0 -37
  89. package/dist/services/redis-cache.js +0 -93
  90. package/dist/services/scheduler.d.ts +0 -40
  91. package/dist/services/scheduler.js +0 -99
  92. package/dist/services/telegram-monitor.d.ts +0 -0
  93. package/dist/services/telegram-monitor.js +0 -118
  94. package/dist/t.d.ts +0 -46
  95. package/dist/t.js +0 -102
  96. package/dist/test.d.ts +0 -0
  97. package/dist/test.js +0 -438
  98. package/dist/types.d.ts +0 -258
  99. package/dist/types.js +0 -22
  100. package/dist/utils/generate-object.d.ts +0 -12
  101. package/dist/utils/header-builder.d.ts +0 -11
  102. package/dist/utils/inject-actions.d.ts +0 -2
  103. package/dist/utils/queue-item-transformer.d.ts +0 -7
  104. package/dist/utils/sanitize-results.d.ts +0 -17
  105. package/dist/utils/schema-generator.d.ts +0 -16
  106. package/examples/index.ts +0 -103
  107. package/llm/interpreter/context.ts +0 -101
  108. package/llm/interpreter/index.ts +0 -136
  109. package/llm/memory-manager/context.ts +0 -21
  110. package/llm/memory-manager/index.ts +0 -163
  111. package/llm/orchestrator/context.ts +0 -22
  112. package/llm/orchestrator/index.ts +0 -232
  113. package/llm/orchestrator/types.ts +0 -14
  114. package/memory/cache.ts +0 -221
  115. package/memory/persistent.ts +0 -265
  116. package/services/redis-cache.ts +0 -128
  117. package/services/scheduler.ts +0 -128
  118. package/services/telegram-monitor.ts +0 -138
  119. package/t.py +0 -79
  120. package/t.spec +0 -38
  121. package/t.ts +0 -133
  122. package/test/llm/orchestrator.test.ts +0 -47
  123. package/test/llm/synthesizer.test.ts +0 -31
  124. package/types.ts +0 -288
  125. /package/dist/{llm/orchestrator/types.js → interfaces/index.js} +0 -0
@@ -1,21 +0,0 @@
1
- import { Character } from "../interpreter/context";
2
-
3
- export const memoryManagerInstructions: Character = {
4
- role: "You are the memory curator. Your role is to extract and format memories from interactions.",
5
- language: "user_request",
6
- guidelines: {
7
- important: [
8
- "Generate memories based on the user request",
9
- "Generate query for requested data as the user could ask for it later",
10
- "Should be short-term memories only if it's ephemeral but relevant and reusable",
11
- "Only store as long-term: User information, User preferences, Important facts that don't change often, Historical milestones",
12
- "Make memory data concise and clear",
13
- "Set appropriate TTL based on data volatility",
14
- ],
15
- warnings: [
16
- "Never store data that is not provided by the results",
17
- "Never store data that is not relevant to the user request",
18
- ],
19
- },
20
- examplesMessages: [],
21
- };
@@ -1,163 +0,0 @@
1
- import { LanguageModelV1 } from "ai";
2
- import { z } from "zod";
3
- import { CacheMemory } from "../../memory/cache";
4
- import { PersistentMemory } from "../../memory/persistent";
5
- import { MemoryScope } from "../../types";
6
- import { generateObject } from "../../utils/generate-object";
7
- import { LLMHeaderBuilder } from "../../utils/header-builder";
8
- import { State } from "../orchestrator/types";
9
- import { memoryManagerInstructions } from "./context";
10
-
11
- interface MemoryResponse {
12
- memories: Array<{
13
- data: string;
14
- type: "short-term" | "long-term";
15
- category:
16
- | "user_information"
17
- | "user_preference"
18
- | "task"
19
- | "current_goal"
20
- | "news"
21
- | "fact"
22
- | "other";
23
- queryForMemory: string;
24
- tags: string[];
25
- ttl: number;
26
- }>;
27
- }
28
- export class MemoryManager {
29
- private readonly model: LanguageModelV1;
30
- private readonly memory?: {
31
- cache?: CacheMemory;
32
- persistent?: PersistentMemory;
33
- };
34
-
35
- constructor(config: {
36
- model: LanguageModelV1;
37
- memory?: {
38
- cache?: CacheMemory;
39
- persistent?: PersistentMemory;
40
- };
41
- }) {
42
- this.model = config.model;
43
- this.memory = config.memory;
44
- }
45
-
46
- buildContext(state: State) {
47
- const context = LLMHeaderBuilder.create()
48
- .addHeader("ROLE", memoryManagerInstructions.role)
49
- .addHeader("LANGUAGE", memoryManagerInstructions.language)
50
- .addHeader("IMPORTANT", memoryManagerInstructions.guidelines.important)
51
- .addHeader("WARNINGS", memoryManagerInstructions.guidelines.warnings)
52
- .addHeader("CURRENT_CONTEXT", state.currentContext)
53
- .addHeader("RESULTS", JSON.stringify(state.results));
54
- return context.toString();
55
- }
56
-
57
- async process(state: State, result: string) {
58
- const context = this.buildContext(state);
59
-
60
- const memories = await generateObject<MemoryResponse>({
61
- model: this.model,
62
- schema: z.object({
63
- memories: z.array(
64
- z.object({
65
- data: z.string(),
66
- type: z.enum(["short-term", "long-term"]),
67
- category: z.enum([
68
- "user_information",
69
- "user_preference",
70
- "task",
71
- "current_goal",
72
- "news",
73
- "fact",
74
- "other",
75
- ]),
76
- queryForData: z.string(),
77
- tags: z.array(z.string()),
78
- ttl: z.number(),
79
- })
80
- ),
81
- }),
82
- prompt: state.currentContext,
83
- system: context.toString(),
84
- temperature: 1,
85
- });
86
-
87
- console.log("Memories:", memories.object.memories);
88
-
89
- if (!this.memory) {
90
- return;
91
- }
92
-
93
- // Store memories after all processing is complete
94
- await Promise.all([
95
- // Store short-term memories in cache
96
- ...memories.object.memories
97
- .filter((m: any) => m.type === "short-term")
98
- .map(async (memoryItem: any) => {
99
- if (!this.memory?.cache) {
100
- return;
101
- }
102
-
103
- const existingCacheMemories =
104
- await this.memory.cache.findSimilarActions(memoryItem.data, {
105
- similarityThreshold: 85,
106
- maxResults: 3,
107
- scope: MemoryScope.GLOBAL,
108
- });
109
-
110
- if (existingCacheMemories.length > 0) {
111
- console.log(
112
- "āš ļø Similar memory already exists in cache:",
113
- memoryItem.data
114
- );
115
- return;
116
- }
117
-
118
- await this.memory.cache.createMemory({
119
- query: memoryItem.queryForMemory,
120
- data: memoryItem.data,
121
- ttl: memoryItem.ttl, // Use TTL from LLM
122
- });
123
- console.log("āœ… Memory stored in cache:", memoryItem.data);
124
- }),
125
-
126
- // Store long-term memories in persistent storage
127
- ...memories.object.memories
128
- .filter((m) => m.type === "long-term")
129
- .map(async (memoryItem) => {
130
- if (!this.memory?.persistent) {
131
- return;
132
- }
133
-
134
- const existingPersistentMemories =
135
- await this.memory.persistent.findRelevantDocuments(
136
- memoryItem.data,
137
- {
138
- similarityThreshold: 85,
139
- }
140
- );
141
-
142
- if (existingPersistentMemories.length > 0) {
143
- console.log(
144
- "āš ļø Similar memory already exists in persistent storage:",
145
- memoryItem.data
146
- );
147
- return;
148
- }
149
-
150
- await this.memory.persistent.createMemory({
151
- query: memoryItem.queryForMemory,
152
- data: memoryItem.data,
153
- category: memoryItem.category,
154
- tags: memoryItem.tags,
155
- roomId: "global",
156
- createdAt: new Date(),
157
- id: crypto.randomUUID(),
158
- });
159
- console.log("āœ… Memory stored in persistent storage:", memoryItem);
160
- }),
161
- ]);
162
- }
163
- }
@@ -1,22 +0,0 @@
1
- import { Character } from "../interpreter/context";
2
-
3
- export const orchestratorInstructions: Character = {
4
- role: "You are the orchestrator. Your role is to evaluate the current state and determine next actions.",
5
- language: "user_request",
6
- guidelines: {
7
- important: [
8
- "Continue executing actions until ALL necessary goals are achieved",
9
- "You can schedule actions in cron expression to be executed later (if needed)",
10
- "Only stop when you have a complete picture of the goal",
11
- "Social responses can be partial while gathering more data",
12
- "Set shouldContinue to false if no more actions are needed",
13
- "Once all actions are completed, choose the right interpreter to interpret the results",
14
- ],
15
- warnings: [
16
- "Never use a tool if it's not related to the user request",
17
- "Never schedule actions that are not related to the user request",
18
- "Never repeat the same action if it's not required to achieve the goal",
19
- "Never repeat scheduled actions if not required to achieve the goal",
20
- ],
21
- },
22
- };
@@ -1,232 +0,0 @@
1
- import { LanguageModelV1 } from "ai";
2
- import { z } from "zod";
3
- import { CacheMemory } from "../../memory/cache";
4
- import { PersistentMemory } from "../../memory/persistent";
5
- import { ActionQueueManager } from "../../services/queue";
6
- import { CacheConfig, RedisCache } from "../../services/redis-cache";
7
- import { TaskScheduler } from "../../services/scheduler";
8
- import {
9
- ActionSchema,
10
- GenerateObjectResponse,
11
- MemoryScope,
12
- QueueCallbacks,
13
- } from "../../types";
14
- import { generateObject } from "../../utils/generate-object";
15
- import { LLMHeaderBuilder } from "../../utils/header-builder";
16
- import { injectActions } from "../../utils/inject-actions";
17
- import { Interpreter } from "../interpreter";
18
- import { orchestratorInstructions } from "./context";
19
- import { State } from "./types";
20
-
21
- export class AgentRuntime {
22
- private readonly model: LanguageModelV1;
23
- private readonly tools: ActionSchema[];
24
- private readonly interpreters: Interpreter[];
25
- private readonly queueManager: ActionQueueManager;
26
- private readonly scheduler: TaskScheduler;
27
- private readonly cache: RedisCache;
28
- private memory?: {
29
- persistent?: PersistentMemory;
30
- cache?: CacheMemory;
31
- };
32
-
33
- constructor(
34
- model: LanguageModelV1,
35
- tools: ActionSchema[],
36
- interpreters: Interpreter[],
37
- redisConfig: CacheConfig,
38
- memory?: {
39
- persistent?: PersistentMemory;
40
- cache?: CacheMemory;
41
- },
42
- callbacks?: QueueCallbacks
43
- ) {
44
- this.model = model;
45
- this.tools = tools;
46
- this.interpreters = interpreters;
47
- this.queueManager = new ActionQueueManager(tools, callbacks);
48
- this.memory = memory;
49
- this.cache = new RedisCache(redisConfig);
50
- this.scheduler = new TaskScheduler(this, this.cache);
51
- }
52
-
53
- private async buildContext(state: State): Promise<string> {
54
- console.log("🧠 Building context with RAG and CAG...");
55
- const context = LLMHeaderBuilder.create();
56
-
57
- // Add orchestrator instructions
58
- context.addHeader("ROLE", orchestratorInstructions.role);
59
- context.addHeader("LANGUAGE", orchestratorInstructions.language);
60
- context.addHeader(
61
- "IMPORTANT",
62
- orchestratorInstructions.guidelines.important
63
- );
64
- context.addHeader("WARNINGS", orchestratorInstructions.guidelines.warnings);
65
- // Add tools to context
66
- context.addHeader("TOOLS", injectActions(this.tools));
67
-
68
- // Add previous actions if any
69
- if (state.previousActions?.length) {
70
- context.addHeader(
71
- "PREVIOUS_ACTIONS",
72
- JSON.stringify(state.previousActions)
73
- );
74
- }
75
-
76
- // Get recent similar actions (CAG)
77
- if (this.memory?.cache) {
78
- const cacheMemories = await this.memory.cache.findSimilarActions(
79
- state.currentContext,
80
- {
81
- similarityThreshold: 80,
82
- maxResults: 3,
83
- scope: MemoryScope.GLOBAL,
84
- }
85
- );
86
-
87
- if (cacheMemories.length > 0) {
88
- context.addHeader("RECENT_ACTIONS", JSON.stringify(cacheMemories));
89
- }
90
- }
91
-
92
- // Get relevant knowledge (RAG)
93
- if (this.memory?.persistent) {
94
- const persistentMemory =
95
- await this.memory.persistent.findRelevantDocuments(
96
- state.currentContext,
97
- {
98
- similarityThreshold: 80,
99
- }
100
- );
101
-
102
- if (persistentMemory.length > 0) {
103
- context.addHeader(
104
- "RELEVANT_KNOWLEDGE",
105
- JSON.stringify(persistentMemory)
106
- );
107
- }
108
- }
109
-
110
- // Add available interpreters
111
- context.addHeader(
112
- "AVAILABLE_INTERPRETERS",
113
- JSON.stringify(this.interpreters.map((i) => i.name))
114
- );
115
- console.log("Context built with memories", context.toString());
116
- return context.toString();
117
- }
118
-
119
- async process(state: State): Promise<{
120
- shouldContinue: boolean;
121
- actions: Array<{
122
- name: string;
123
- parameters: Array<{
124
- name: string;
125
- value: any;
126
- }>;
127
- scheduler?: {
128
- isScheduled: boolean;
129
- scheduledAtInC?: string;
130
- interval?: string;
131
- reason?: string;
132
- };
133
- }>;
134
- socialResponse?: {
135
- shouldRespond: boolean;
136
- response?: string;
137
- isPartialResponse?: boolean;
138
- };
139
- interpreter?: string;
140
- results?: string;
141
- }> {
142
- console.log("šŸ”„ Processing state:");
143
- console.dir(state, { depth: null });
144
- if (state.previousActions?.length) {
145
- console.log(
146
- "šŸ“Š Previous actions:",
147
- state.previousActions
148
- .map((a) => (typeof a === "string" ? a : a.name))
149
- .join(", ")
150
- );
151
- }
152
-
153
- const context = await this.buildContext(state);
154
-
155
- console.log("\n🧠 Generating response from LLM...");
156
- const response = await generateObject<GenerateObjectResponse>({
157
- model: this.model,
158
- schema: z.object({
159
- shouldContinue: z.boolean(),
160
- actions: z.array(
161
- z.object({
162
- name: z.string(),
163
- parameters: z.array(
164
- z.object({
165
- name: z.string(),
166
- value: z.any(),
167
- })
168
- ),
169
- scheduler: z
170
- .object({
171
- isScheduled: z.boolean(),
172
- cronExpression: z.string().optional(),
173
- reason: z.string().optional(),
174
- })
175
- .optional(),
176
- })
177
- ),
178
- socialResponse: z
179
- .object({
180
- shouldRespond: z.boolean(),
181
- response: z.string().optional(),
182
- isPartialResponse: z.boolean().optional(),
183
- })
184
- .optional(),
185
- interpreter: z.string().optional(),
186
- }),
187
- prompt: state.currentContext,
188
- system: context.toString(),
189
- temperature: 0,
190
- });
191
- console.log("šŸ”„ Orchestrator response:");
192
- console.dir(response.object, { depth: null });
193
-
194
- // Force shouldContinue to false if no actions are planned
195
- if (response.object.actions.length === 0) {
196
- response.object.shouldContinue = false;
197
- console.log("āš ļø No actions planned, forcing shouldContinue to false");
198
- }
199
-
200
- // Handle social interactions and actions in a single block
201
- if (response.object.socialResponse?.shouldRespond) {
202
- console.log("\nšŸ’¬ Processing social response");
203
- if (response.object.socialResponse.response) {
204
- console.log("šŸ“¢ Response:", response.object.socialResponse.response);
205
- // Ensure all parameters have a value property
206
- }
207
- }
208
-
209
- // Handle scheduled actions
210
- for (const action of response.object.actions) {
211
- if (action.scheduler?.isScheduled) {
212
- await this.scheduler.scheduleRequest({
213
- originalRequest: state.currentContext,
214
- cronExpression: action.scheduler.cronExpression,
215
- });
216
- }
217
- }
218
-
219
- // Store actions in Redis cache
220
- if (response.object.actions.length > 0) {
221
- const requestId = crypto.randomUUID();
222
- await this.cache.storePreviousActions(requestId, response.object.actions);
223
- }
224
-
225
- // Store message in recent messages
226
- await this.cache.storeRecentMessage(state.currentContext, {
227
- socialResponse: response.object.socialResponse,
228
- });
229
-
230
- return response.object;
231
- }
232
- }
@@ -1,14 +0,0 @@
1
- import { QueueResult } from "../../types";
2
-
3
- export interface State {
4
- currentContext: string;
5
- previousActions: (string | QueueResult)[];
6
- reward?: number;
7
- userRequest?: string;
8
- results?: string;
9
- }
10
-
11
- export interface Action {
12
- name: string;
13
- parameters: Record<string, any>;
14
- }
package/memory/cache.ts DELETED
@@ -1,221 +0,0 @@
1
- import { openai } from "@ai-sdk/openai";
2
- import { cosineSimilarity, embed, EmbeddingModel } from "ai";
3
- import { createClient } from "redis";
4
- import {
5
- CacheMemoryOptions,
6
- CacheMemoryType,
7
- CreateMemoryInput,
8
- MatchOptions,
9
- MemoryScope,
10
- } from "../types";
11
-
12
- export class CacheMemory {
13
- private redis;
14
- private readonly CACHE_PREFIX: string;
15
- private readonly CACHE_TTL: number;
16
- private readonly embeddingModel: EmbeddingModel<string>;
17
-
18
- constructor(options: CacheMemoryOptions) {
19
- this.embeddingModel = options.embeddingModel;
20
- const ttlInHours = options.cacheTTL ?? 1;
21
- this.CACHE_TTL = ttlInHours * 60 * 60;
22
- this.CACHE_PREFIX = options.cachePrefix ?? "memory:";
23
-
24
- this.redis = createClient({
25
- url: options.redisUrl || process.env.REDIS_URL,
26
- socket: {
27
- tls: true,
28
- rejectUnauthorized: true,
29
- },
30
- });
31
- this.initRedis();
32
- }
33
-
34
- private async initRedis() {
35
- this.redis.on("error", (err) => {
36
- console.error("āŒ Redis Client Error:", err);
37
- });
38
-
39
- try {
40
- await this.redis.connect();
41
- console.log("āœ… Successfully connected to Redis");
42
- } catch (error) {
43
- console.error("āŒ Failed to connect to Redis:", error);
44
- }
45
- }
46
-
47
- private async storeMemory(memory: CacheMemoryType, ttl?: number) {
48
- const prefix = this.CACHE_PREFIX;
49
- const key = `${prefix}${memory.id}`;
50
- const result = await this.redis.set(key, JSON.stringify(memory), {
51
- EX: ttl || this.CACHE_TTL,
52
- });
53
- console.log("šŸ’¾ Cache memory created:", result);
54
- }
55
-
56
- async findSimilarActions(
57
- query: string,
58
- options: MatchOptions & { userId?: string; scope?: MemoryScope } = {}
59
- ): Promise<
60
- {
61
- data: any;
62
- query: string;
63
- createdAt: Date;
64
- }[]
65
- > {
66
- console.log("\nšŸ” Searching in cache");
67
- console.log("Query:", query);
68
- console.log("Options:", JSON.stringify(options, null, 2));
69
-
70
- const { embedding } = await embed({
71
- model: openai.embedding("text-embedding-3-small"),
72
- value: query,
73
- });
74
-
75
- const memories = await this.getAllMemories();
76
- console.log(`\nšŸ“š Found ${memories.length} cached queries to compare`);
77
-
78
- const matches = memories
79
- .map((memory) => {
80
- const similarity = cosineSimilarity(embedding, memory.embedding);
81
- const similarityPercentage = (similarity + 1) * 50;
82
- return {
83
- data: memory.data,
84
- query: memory.query,
85
- similarityPercentage,
86
- createdAt: memory.createdAt,
87
- };
88
- })
89
- .filter(
90
- (match) =>
91
- match.similarityPercentage >= (options.similarityThreshold ?? 70)
92
- )
93
- .sort((a, b) => b.similarityPercentage - a.similarityPercentage);
94
-
95
- const results = options.maxResults
96
- ? matches.slice(0, options.maxResults)
97
- : matches;
98
-
99
- if (results.length > 0) {
100
- console.log("\n✨ Similar queries found:");
101
- console.log("─".repeat(50));
102
-
103
- results.forEach((match, index) => {
104
- console.log(`\n${index + 1}. Match Details:`);
105
- console.log(` Query: ${match.query}`);
106
- console.log(` Data: ${JSON.stringify(match.data)}`);
107
- console.log(` Similarity: ${match.similarityPercentage.toFixed(2)}%`);
108
- console.log("─".repeat(50));
109
- });
110
- } else {
111
- console.log("\nāŒ No similar queries found in cache");
112
- }
113
-
114
- return results.map((match) => {
115
- return {
116
- data: match.data,
117
- query: match.query,
118
- createdAt: match.createdAt,
119
- };
120
- });
121
- }
122
-
123
- async getAllMemories(): Promise<CacheMemoryType[]> {
124
- const keys = await this.redis.keys(`${this.CACHE_PREFIX}*`);
125
- const memories = await this.getMemoriesFromKeys(keys);
126
-
127
- return memories;
128
- }
129
-
130
- private async getMemoriesFromKeys(
131
- keys: string[]
132
- ): Promise<CacheMemoryType[]> {
133
- const memories: CacheMemoryType[] = [];
134
- for (const key of keys) {
135
- const data = await this.redis.get(key);
136
- if (data) {
137
- memories.push(JSON.parse(data));
138
- }
139
- }
140
- return memories;
141
- }
142
-
143
- public async createMemory(
144
- input: CreateMemoryInput
145
- ): Promise<CacheMemoryType | undefined> {
146
- console.log("\nšŸ“ Processing new memory creation");
147
- console.log("Content:", input.query);
148
- console.log("TTL:", input.ttl ? `${input.ttl} seconds` : "default");
149
-
150
- const existingPattern = await this.findSimilarActions(input.query, {
151
- similarityThreshold: 95,
152
- userId: input.userId,
153
- scope: input.scope,
154
- });
155
-
156
- if (existingPattern.length > 0) {
157
- console.log("\nšŸ”„ Similar cache memory already exists");
158
- console.log("─".repeat(50));
159
- existingPattern.forEach((match, index) => {
160
- console.log(`\n${index + 1}. Existing Match:`);
161
- console.log(` Query: ${match.query}`);
162
- console.log(` Data: ${JSON.stringify(match.data)}`);
163
- console.log(` Created At: ${match.createdAt}`);
164
- });
165
- console.log("\nā­ļø Skipping creation of new memory");
166
- return;
167
- }
168
-
169
- console.log("\nšŸ†• No similar memory found - creating new one");
170
-
171
- const memory = await this.createSingleMemory({
172
- id: crypto.randomUUID(),
173
- query: input.query,
174
- data: input.data,
175
- userId: input.userId,
176
- scope: input.scope,
177
- ttl: input.ttl,
178
- });
179
-
180
- return memory;
181
- }
182
-
183
- private async createSingleMemory(params: {
184
- id: string;
185
- query: string;
186
- data: any;
187
- userId?: string;
188
- scope?: MemoryScope;
189
- ttl?: number;
190
- }): Promise<CacheMemoryType> {
191
- console.log("\nšŸ—ļø Creating new cache memory");
192
- console.log("ID:", params.id);
193
- console.log("Content:", params.query);
194
-
195
- console.log("\n🧮 Generating embedding...");
196
- const { embedding } = await embed({
197
- model: this.embeddingModel,
198
- value: params.query,
199
- });
200
- console.log("āœ… Embedding generated successfully");
201
-
202
- const memory: CacheMemoryType = {
203
- id: params.id,
204
- data: params.data,
205
- query: params.query,
206
- embedding,
207
- userId: params.userId,
208
- scope:
209
- params.scope || (params.userId ? MemoryScope.USER : MemoryScope.GLOBAL),
210
- createdAt: new Date(),
211
- };
212
-
213
- await this.storeMemory(memory, params.ttl);
214
- console.log("āœ… Short-term memory created and stored successfully", {
215
- ...memory,
216
- ttl: params.ttl || this.CACHE_TTL,
217
- });
218
-
219
- return memory;
220
- }
221
- }