@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,22 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.memoryManagerInstructions = void 0;
4
- exports.memoryManagerInstructions = {
5
- role: "You are the memory curator. Your role is to extract and format memories from interactions.",
6
- language: "user_request",
7
- guidelines: {
8
- important: [
9
- "Generate memories based on the user request",
10
- "Generate query for requested data as the user could ask for it later",
11
- "Should be short-term memories only if it's ephemeral but relevant and reusable",
12
- "Only store as long-term: User information, User preferences, Important facts that don't change often, Historical milestones",
13
- "Make memory data concise and clear",
14
- "Set appropriate TTL based on data volatility",
15
- ],
16
- warnings: [
17
- "Never store data that is not provided by the results",
18
- "Never store data that is not relevant to the user request",
19
- ],
20
- },
21
- examplesMessages: [],
22
- };
@@ -1,17 +0,0 @@
1
- import { LanguageModelV1 } from "ai";
2
- import { CacheMemory } from "../../memory/cache";
3
- import { PersistentMemory } from "../../memory/persistent";
4
- import { State } from "../orchestrator/types";
5
- export declare class MemoryManager {
6
- private readonly model;
7
- private readonly memory?;
8
- constructor(config: {
9
- model: LanguageModelV1;
10
- memory?: {
11
- cache?: CacheMemory;
12
- persistent?: PersistentMemory;
13
- };
14
- });
15
- buildContext(state: State): string;
16
- process(state: State, result: string): Promise<void>;
17
- }
@@ -1,107 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MemoryManager = void 0;
4
- const zod_1 = require("zod");
5
- const types_1 = require("../../types");
6
- const generate_object_1 = require("../../utils/generate-object");
7
- const header_builder_1 = require("../../utils/header-builder");
8
- const context_1 = require("./context");
9
- class MemoryManager {
10
- constructor(config) {
11
- this.model = config.model;
12
- this.memory = config.memory;
13
- }
14
- buildContext(state) {
15
- const context = header_builder_1.LLMHeaderBuilder.create()
16
- .addHeader("ROLE", context_1.memoryManagerInstructions.role)
17
- .addHeader("LANGUAGE", context_1.memoryManagerInstructions.language)
18
- .addHeader("IMPORTANT", context_1.memoryManagerInstructions.guidelines.important)
19
- .addHeader("WARNINGS", context_1.memoryManagerInstructions.guidelines.warnings)
20
- .addHeader("CURRENT_CONTEXT", state.currentContext)
21
- .addHeader("RESULTS", JSON.stringify(state.results));
22
- return context.toString();
23
- }
24
- async process(state, result) {
25
- const context = this.buildContext(state);
26
- const memories = await (0, generate_object_1.generateObject)({
27
- model: this.model,
28
- schema: zod_1.z.object({
29
- memories: zod_1.z.array(zod_1.z.object({
30
- data: zod_1.z.string(),
31
- type: zod_1.z.enum(["short-term", "long-term"]),
32
- category: zod_1.z.enum([
33
- "user_information",
34
- "user_preference",
35
- "task",
36
- "current_goal",
37
- "news",
38
- "fact",
39
- "other",
40
- ]),
41
- queryForData: zod_1.z.string(),
42
- tags: zod_1.z.array(zod_1.z.string()),
43
- ttl: zod_1.z.number(),
44
- })),
45
- }),
46
- prompt: state.currentContext,
47
- system: context.toString(),
48
- temperature: 1,
49
- });
50
- console.log("Memories:", memories.object.memories);
51
- if (!this.memory) {
52
- return;
53
- }
54
- // Store memories after all processing is complete
55
- await Promise.all([
56
- // Store short-term memories in cache
57
- ...memories.object.memories
58
- .filter((m) => m.type === "short-term")
59
- .map(async (memoryItem) => {
60
- if (!this.memory?.cache) {
61
- return;
62
- }
63
- const existingCacheMemories = await this.memory.cache.findSimilarActions(memoryItem.data, {
64
- similarityThreshold: 85,
65
- maxResults: 3,
66
- scope: types_1.MemoryScope.GLOBAL,
67
- });
68
- if (existingCacheMemories.length > 0) {
69
- console.log("⚠️ Similar memory already exists in cache:", memoryItem.data);
70
- return;
71
- }
72
- await this.memory.cache.createMemory({
73
- query: memoryItem.queryForMemory,
74
- data: memoryItem.data,
75
- ttl: memoryItem.ttl, // Use TTL from LLM
76
- });
77
- console.log("✅ Memory stored in cache:", memoryItem.data);
78
- }),
79
- // Store long-term memories in persistent storage
80
- ...memories.object.memories
81
- .filter((m) => m.type === "long-term")
82
- .map(async (memoryItem) => {
83
- if (!this.memory?.persistent) {
84
- return;
85
- }
86
- const existingPersistentMemories = await this.memory.persistent.findRelevantDocuments(memoryItem.data, {
87
- similarityThreshold: 85,
88
- });
89
- if (existingPersistentMemories.length > 0) {
90
- console.log("⚠️ Similar memory already exists in persistent storage:", memoryItem.data);
91
- return;
92
- }
93
- await this.memory.persistent.createMemory({
94
- query: memoryItem.queryForMemory,
95
- data: memoryItem.data,
96
- category: memoryItem.category,
97
- tags: memoryItem.tags,
98
- roomId: "global",
99
- createdAt: new Date(),
100
- id: crypto.randomUUID(),
101
- });
102
- console.log("✅ Memory stored in persistent storage:", memoryItem);
103
- }),
104
- ]);
105
- }
106
- }
107
- exports.MemoryManager = MemoryManager;
@@ -1,2 +0,0 @@
1
- import { Character } from "../interpreter/context";
2
- export declare const orchestratorInstructions: Character;
@@ -1,23 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.orchestratorInstructions = void 0;
4
- exports.orchestratorInstructions = {
5
- role: "You are the orchestrator. Your role is to evaluate the current state and determine next actions.",
6
- language: "user_request",
7
- guidelines: {
8
- important: [
9
- "Continue executing actions until ALL necessary goals are achieved",
10
- "You can schedule actions in cron expression to be executed later (if needed)",
11
- "Only stop when you have a complete picture of the goal",
12
- "Social responses can be partial while gathering more data",
13
- "Set shouldContinue to false if no more actions are needed",
14
- "Once all actions are completed, choose the right interpreter to interpret the results",
15
- ],
16
- warnings: [
17
- "Never use a tool if it's not related to the user request",
18
- "Never schedule actions that are not related to the user request",
19
- "Never repeat the same action if it's not required to achieve the goal",
20
- "Never repeat scheduled actions if not required to achieve the goal",
21
- ],
22
- },
23
- };
@@ -1,44 +0,0 @@
1
- import { LanguageModelV1 } from "ai";
2
- import { CacheMemory } from "../../memory/cache";
3
- import { PersistentMemory } from "../../memory/persistent";
4
- import { CacheConfig } from "../../services/redis-cache";
5
- import { ActionSchema, QueueCallbacks } from "../../types";
6
- import { Interpreter } from "../interpreter";
7
- import { State } from "./types";
8
- export declare class AgentRuntime {
9
- private readonly model;
10
- private readonly tools;
11
- private readonly interpreters;
12
- private readonly queueManager;
13
- private readonly scheduler;
14
- private readonly cache;
15
- private memory?;
16
- constructor(model: LanguageModelV1, tools: ActionSchema[], interpreters: Interpreter[], redisConfig: CacheConfig, memory?: {
17
- persistent?: PersistentMemory;
18
- cache?: CacheMemory;
19
- }, callbacks?: QueueCallbacks);
20
- private buildContext;
21
- process(state: State): Promise<{
22
- shouldContinue: boolean;
23
- actions: Array<{
24
- name: string;
25
- parameters: Array<{
26
- name: string;
27
- value: any;
28
- }>;
29
- scheduler?: {
30
- isScheduled: boolean;
31
- scheduledAtInC?: string;
32
- interval?: string;
33
- reason?: string;
34
- };
35
- }>;
36
- socialResponse?: {
37
- shouldRespond: boolean;
38
- response?: string;
39
- isPartialResponse?: boolean;
40
- };
41
- interpreter?: string;
42
- results?: string;
43
- }>;
44
- }
@@ -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
- }
@@ -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
- }
@@ -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 {};