@ai.ntellect/core 0.0.24 → 0.0.26

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.
@@ -1,13 +1,4 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
2
  Object.defineProperty(exports, "__esModule", { value: true });
12
3
  exports.MemoryCache = void 0;
13
4
  const openai_1 = require("@ai-sdk/openai");
@@ -17,10 +8,9 @@ const zod_1 = require("zod");
17
8
  const types_1 = require("../types");
18
9
  class MemoryCache {
19
10
  constructor(options = {}) {
20
- var _a, _b;
21
- const ttlInHours = (_a = options.cacheTTL) !== null && _a !== void 0 ? _a : 1;
11
+ const ttlInHours = options.cacheTTL ?? 1;
22
12
  this.CACHE_TTL = ttlInHours * 60 * 60;
23
- this.CACHE_PREFIX = (_b = options.cachePrefix) !== null && _b !== void 0 ? _b : 'memory:';
13
+ this.CACHE_PREFIX = options.cachePrefix ?? 'memory:';
24
14
  this.redis = (0, redis_1.createClient)({
25
15
  url: options.redisUrl || process.env.REDIS_URL,
26
16
  socket: {
@@ -30,21 +20,19 @@ class MemoryCache {
30
20
  });
31
21
  this.initRedis();
32
22
  }
33
- initRedis() {
34
- return __awaiter(this, void 0, void 0, function* () {
35
- this.redis.on('error', err => {
36
- console.error('Redis Client Error:', err);
37
- // Implement retry logic if needed
38
- });
39
- try {
40
- yield this.redis.connect();
41
- console.log('Successfully connected to Redis');
42
- }
43
- catch (error) {
44
- console.error('Failed to connect to Redis:', error);
45
- // Handle connection failure
46
- }
23
+ async initRedis() {
24
+ this.redis.on('error', err => {
25
+ console.error('Redis Client Error:', err);
26
+ // Implement retry logic if needed
47
27
  });
28
+ try {
29
+ await this.redis.connect();
30
+ console.log('Successfully connected to Redis');
31
+ }
32
+ catch (error) {
33
+ console.error('Failed to connect to Redis:', error);
34
+ // Handle connection failure
35
+ }
48
36
  }
49
37
  getMemoryKey(scope, userId) {
50
38
  if (scope === types_1.MemoryScope.GLOBAL) {
@@ -52,139 +40,129 @@ class MemoryCache {
52
40
  }
53
41
  return `${this.CACHE_PREFIX}user:${userId}:`;
54
42
  }
55
- storeMemory(memory) {
56
- return __awaiter(this, void 0, void 0, function* () {
57
- const prefix = this.getMemoryKey(memory.scope, memory.userId);
58
- const key = `${prefix}${memory.id}`;
59
- yield this.redis.set(key, JSON.stringify(memory), {
60
- EX: this.CACHE_TTL
61
- });
43
+ async storeMemory(memory) {
44
+ const prefix = this.getMemoryKey(memory.scope, memory.userId);
45
+ const key = `${prefix}${memory.id}`;
46
+ await this.redis.set(key, JSON.stringify(memory), {
47
+ EX: this.CACHE_TTL
62
48
  });
63
49
  }
64
- findBestMatches(query_1) {
65
- return __awaiter(this, arguments, void 0, function* (query, options = {}) {
66
- console.log("\n🔍 Searching for query:", query);
67
- const { embedding } = yield (0, ai_1.embed)({
68
- model: openai_1.openai.embedding("text-embedding-3-small"),
69
- value: query
50
+ async findBestMatches(query, options = {}) {
51
+ console.log("\n🔍 Searching for query:", query);
52
+ const { embedding } = await (0, ai_1.embed)({
53
+ model: openai_1.openai.embedding("text-embedding-3-small"),
54
+ value: query
55
+ });
56
+ const memories = await this.getAllMemories(options.scope, options.userId);
57
+ console.log("\n📚 Found", memories.length, "memories to compare with");
58
+ const matches = memories
59
+ .map(memory => {
60
+ const similarities = memory.embeddings.map(emb => {
61
+ const similarity = (0, ai_1.cosineSimilarity)(embedding, emb);
62
+ return (similarity + 1) * 50; // Convert to percentage
70
63
  });
71
- const memories = yield this.getAllMemories(options.scope, options.userId);
72
- console.log("\n📚 Found", memories.length, "memories to compare with");
73
- const matches = memories
74
- .map(memory => {
75
- const similarities = memory.embeddings.map(emb => {
76
- const similarity = (0, ai_1.cosineSimilarity)(embedding, emb);
77
- return (similarity + 1) * 50; // Convert to percentage
78
- });
79
- const maxSimilarity = Math.max(...similarities);
80
- console.log(`\n📊 Memory "${memory.purpose}":
64
+ const maxSimilarity = Math.max(...similarities);
65
+ console.log(`\n📊 Memory "${memory.purpose}":
81
66
  - Similarity: ${maxSimilarity.toFixed(2)}%
82
67
  - Original queries: ${memory.queries.join(", ")}`);
83
- return {
84
- data: memory.data,
85
- similarityPercentage: maxSimilarity,
86
- purpose: memory.purpose,
87
- };
88
- })
89
- .filter(match => { var _a; return match.similarityPercentage >= ((_a = options.similarityThreshold) !== null && _a !== void 0 ? _a : 70); })
90
- .sort((a, b) => b.similarityPercentage - a.similarityPercentage);
91
- const results = options.maxResults ? matches.slice(0, options.maxResults) : matches;
92
- if (results.length > 0) {
93
- console.log("\n✨ Best matches found:");
94
- results.forEach(match => {
95
- console.log(`- ${match.purpose} (${match.similarityPercentage.toFixed(2)}%)`);
96
- });
97
- }
98
- else {
99
- console.log("No matches found");
100
- }
101
- console.dir({ results });
102
- return results;
103
- });
68
+ return {
69
+ data: memory.data,
70
+ similarityPercentage: maxSimilarity,
71
+ purpose: memory.purpose,
72
+ };
73
+ })
74
+ .filter(match => match.similarityPercentage >= (options.similarityThreshold ?? 70))
75
+ .sort((a, b) => b.similarityPercentage - a.similarityPercentage);
76
+ const results = options.maxResults ? matches.slice(0, options.maxResults) : matches;
77
+ if (results.length > 0) {
78
+ console.log("\n✨ Best matches found:");
79
+ results.forEach(match => {
80
+ console.log(`- ${match.purpose} (${match.similarityPercentage.toFixed(2)}%)`);
81
+ });
82
+ }
83
+ else {
84
+ console.log("No matches found");
85
+ }
86
+ console.dir({ results });
87
+ return results;
104
88
  }
105
- getAllMemories(scope, userId) {
106
- return __awaiter(this, void 0, void 0, function* () {
107
- let patterns = [];
108
- if (!scope || scope === types_1.MemoryScope.GLOBAL) {
109
- const globalPrefix = this.getMemoryKey(types_1.MemoryScope.GLOBAL);
110
- const globalKeys = yield this.redis.keys(`${globalPrefix}*`);
111
- const globalPatterns = yield this.getMemoriesFromKeys(globalKeys);
112
- patterns = patterns.concat(globalPatterns);
113
- }
114
- if (userId && (!scope || scope === types_1.MemoryScope.USER)) {
115
- const userPrefix = this.getMemoryKey(types_1.MemoryScope.USER, userId);
116
- const userKeys = yield this.redis.keys(`${userPrefix}*`);
117
- const userPatterns = yield this.getMemoriesFromKeys(userKeys);
118
- patterns = patterns.concat(userPatterns);
119
- }
120
- return patterns;
121
- });
89
+ async getAllMemories(scope, userId) {
90
+ let patterns = [];
91
+ if (!scope || scope === types_1.MemoryScope.GLOBAL) {
92
+ const globalPrefix = this.getMemoryKey(types_1.MemoryScope.GLOBAL);
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;
122
104
  }
123
- getMemoriesFromKeys(keys) {
124
- return __awaiter(this, void 0, void 0, function* () {
125
- const memories = [];
126
- for (const key of keys) {
127
- const data = yield this.redis.get(key);
128
- if (data) {
129
- memories.push(JSON.parse(data));
130
- }
105
+ async getMemoriesFromKeys(keys) {
106
+ const memories = [];
107
+ for (const key of keys) {
108
+ const data = await this.redis.get(key);
109
+ if (data) {
110
+ memories.push(JSON.parse(data));
131
111
  }
132
- return memories;
133
- });
112
+ }
113
+ return memories;
134
114
  }
135
- createMemory(input) {
136
- return __awaiter(this, void 0, void 0, function* () {
137
- const { embedding } = yield (0, ai_1.embed)({
138
- model: openai_1.openai.embedding("text-embedding-3-small"),
139
- value: input.content
140
- });
141
- const existingPattern = yield this.findBestMatches(input.content, {
142
- similarityThreshold: 95,
143
- userId: input.userId,
144
- scope: input.scope
115
+ async createMemory(input) {
116
+ const { embedding } = await (0, ai_1.embed)({
117
+ model: openai_1.openai.embedding("text-embedding-3-small"),
118
+ value: input.content
119
+ });
120
+ const existingPattern = await this.findBestMatches(input.content, {
121
+ similarityThreshold: 95,
122
+ userId: input.userId,
123
+ scope: input.scope
124
+ });
125
+ if (existingPattern.length > 0) {
126
+ console.log("\n🔍 Similar memory found:");
127
+ // Display only the name and similarity percentage
128
+ existingPattern.forEach(match => {
129
+ console.log(`- ${match.purpose} (${match.similarityPercentage.toFixed(2)}%)`);
145
130
  });
146
- if (existingPattern.length > 0) {
147
- console.log("\n🔍 Similar memory found:");
148
- // Display only the name and similarity percentage
149
- existingPattern.forEach(match => {
150
- console.log(`- ${match.purpose} (${match.similarityPercentage.toFixed(2)}%)`);
151
- });
152
- return;
153
- }
154
- const variations = yield (0, ai_1.generateObject)({
155
- model: (0, openai_1.openai)("gpt-4"),
156
- schema: zod_1.z.object({
157
- request: zod_1.z.string().describe("The request to be performed"),
158
- queries: zod_1.z.array(zod_1.z.object({
159
- text: zod_1.z.string()
160
- }))
161
- }),
162
- prompt: `For this input: "${input.content}"
131
+ return;
132
+ }
133
+ const variations = await (0, ai_1.generateObject)({
134
+ model: (0, openai_1.openai)("gpt-4"),
135
+ schema: zod_1.z.object({
136
+ request: zod_1.z.string().describe("The request to be performed"),
137
+ queries: zod_1.z.array(zod_1.z.object({
138
+ text: zod_1.z.string()
139
+ }))
140
+ }),
141
+ prompt: `For this input: "${input.content}"
163
142
  Generate similar variations that should match the same context.
164
143
  Context type: ${input.type}
165
144
  Data: ${JSON.stringify(input.data)}
166
145
  - Keep variations natural and human-like
167
146
  - Include the original input
168
147
  - Add 3-5 variations`
169
- });
170
- const embeddingResults = yield (0, ai_1.embedMany)({
171
- model: openai_1.openai.embedding("text-embedding-3-small"),
172
- values: variations.object.queries.map(q => q.text)
173
- });
174
- const memory = {
175
- id: crypto.randomUUID(),
176
- type: input.type,
177
- data: input.data,
178
- purpose: variations.object.request,
179
- queries: [input.content, ...variations.object.queries.map(q => q.text)],
180
- embeddings: [embedding, ...embeddingResults.embeddings],
181
- userId: input.userId,
182
- scope: input.scope || (input.userId ? types_1.MemoryScope.USER : types_1.MemoryScope.GLOBAL),
183
- createdAt: new Date()
184
- };
185
- yield this.storeMemory(memory);
186
- return variations.object.request;
187
148
  });
149
+ const embeddingResults = await (0, ai_1.embedMany)({
150
+ model: openai_1.openai.embedding("text-embedding-3-small"),
151
+ values: variations.object.queries.map(q => q.text)
152
+ });
153
+ const memory = {
154
+ id: crypto.randomUUID(),
155
+ type: input.type,
156
+ data: input.data,
157
+ purpose: variations.object.request,
158
+ queries: [input.content, ...variations.object.queries.map(q => q.text)],
159
+ embeddings: [embedding, ...embeddingResults.embeddings],
160
+ userId: input.userId,
161
+ scope: input.scope || (input.userId ? types_1.MemoryScope.USER : types_1.MemoryScope.GLOBAL),
162
+ createdAt: new Date()
163
+ };
164
+ await this.storeMemory(memory);
165
+ return variations.object.request;
188
166
  }
189
167
  }
190
168
  exports.MemoryCache = MemoryCache;
@@ -0,0 +1,13 @@
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,13 +1,4 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
2
  Object.defineProperty(exports, "__esModule", { value: true });
12
3
  exports.ActionQueueManager = void 0;
13
4
  class ActionQueueManager {
@@ -20,7 +11,7 @@ class ActionQueueManager {
20
11
  }
21
12
  addToQueue(actions) {
22
13
  if (Array.isArray(actions)) {
23
- console.log("Adding actions to queue:", actions.map(a => a.name).join(", "));
14
+ console.log("Adding actions to queue:", actions.map((a) => a.name).join(", "));
24
15
  this.queue.push(...actions);
25
16
  }
26
17
  else {
@@ -28,64 +19,60 @@ class ActionQueueManager {
28
19
  this.queue.push(actions);
29
20
  }
30
21
  }
31
- processQueue() {
32
- return __awaiter(this, void 0, void 0, function* () {
33
- var _a, _b, _c, _d, _e;
34
- if (this.isProcessing) {
35
- console.warn("Queue is already being processed");
36
- return;
37
- }
38
- this.isProcessing = true;
39
- const actionPromises = [];
40
- for (const action of this.queue) {
41
- const actionConfig = this.actions.find((a) => a.name === action.name);
42
- if ((_a = actionConfig === null || actionConfig === void 0 ? void 0 : actionConfig.confirmation) === null || _a === void 0 ? void 0 : _a.requireConfirmation) {
43
- // Wait for user confirmation before executing this action
44
- const shouldProceed = yield ((_c = (_b = this.callbacks).onConfirmationRequired) === null || _c === void 0 ? void 0 : _c.call(_b, actionConfig.confirmation.message || `Do you want to proceed with action: ${action.name}?`));
45
- if (!shouldProceed) {
46
- // Skip this action and add a cancelled result
47
- this.results.push({
48
- name: action.name,
49
- parameters: this.formatArguments(action.parameters),
50
- result: null,
51
- error: "Action cancelled by user",
52
- cancelled: true
53
- });
54
- continue;
55
- }
56
- }
57
- actionPromises.push(this.executeAction(action)
58
- .then((result) => {
59
- var _a, _b;
60
- (_b = (_a = this.callbacks).onActionComplete) === null || _b === void 0 ? void 0 : _b.call(_a, result);
61
- return result;
62
- })
63
- .catch((error) => {
64
- var _a, _b;
65
- const result = {
22
+ async processQueue() {
23
+ if (this.isProcessing) {
24
+ console.warn("Queue is already being processed");
25
+ return;
26
+ }
27
+ this.isProcessing = true;
28
+ const actionPromises = [];
29
+ for (const action of this.queue) {
30
+ const actionConfig = this.actions.find((a) => a.name === action.name);
31
+ if (actionConfig?.confirmation?.requireConfirmation) {
32
+ // Wait for user confirmation before executing this action
33
+ const shouldProceed = await this.callbacks.onConfirmationRequired?.(actionConfig.confirmation.message ||
34
+ `Do you want to proceed with action: ${action.name}?`);
35
+ if (!shouldProceed) {
36
+ // Skip this action and add a cancelled result
37
+ this.results.push({
66
38
  name: action.name,
67
39
  parameters: this.formatArguments(action.parameters),
68
40
  result: null,
69
- error: error.message || "Unknown error occurred"
70
- };
71
- (_b = (_a = this.callbacks).onActionComplete) === null || _b === void 0 ? void 0 : _b.call(_a, result);
72
- return result;
73
- }));
74
- }
75
- try {
76
- const results = yield Promise.all(actionPromises);
77
- this.results.push(...results);
78
- this.queue = [];
79
- (_e = (_d = this.callbacks).onQueueComplete) === null || _e === void 0 ? void 0 : _e.call(_d, this.results);
80
- this.isProcessing = false;
81
- return this.results;
82
- }
83
- catch (error) {
84
- this.isProcessing = false;
85
- console.error("Unexpected error in queue processing:", error);
86
- throw error;
41
+ error: "Action cancelled by user",
42
+ cancelled: true,
43
+ });
44
+ continue;
45
+ }
87
46
  }
88
- });
47
+ actionPromises.push(this.executeAction(action)
48
+ .then((result) => {
49
+ this.callbacks.onActionComplete?.(result);
50
+ return result;
51
+ })
52
+ .catch((error) => {
53
+ const result = {
54
+ name: action.name,
55
+ parameters: this.formatArguments(action.parameters),
56
+ result: null,
57
+ error: error.message || "Unknown error occurred",
58
+ };
59
+ this.callbacks.onActionComplete?.(result);
60
+ return result;
61
+ }));
62
+ }
63
+ try {
64
+ const results = await Promise.all(actionPromises);
65
+ this.results.push(...results);
66
+ this.queue = [];
67
+ this.callbacks.onQueueComplete?.(this.results);
68
+ this.isProcessing = false;
69
+ return this.results;
70
+ }
71
+ catch (error) {
72
+ this.isProcessing = false;
73
+ console.error("Unexpected error in queue processing:", error);
74
+ throw error;
75
+ }
89
76
  }
90
77
  formatArguments(args) {
91
78
  return args.reduce((acc, arg) => {
@@ -93,44 +80,45 @@ class ActionQueueManager {
93
80
  return acc;
94
81
  }, {});
95
82
  }
96
- executeAction(action) {
97
- return __awaiter(this, void 0, void 0, function* () {
98
- var _a, _b;
99
- // Call onActionStart callback
100
- (_b = (_a = this.callbacks).onActionStart) === null || _b === void 0 ? void 0 : _b.call(_a, action);
101
- const actionConfig = this.actions.find((a) => a.name === action.name);
102
- if (!actionConfig) {
103
- return {
104
- name: action.name,
105
- parameters: {},
106
- result: null,
107
- error: `Action '${action.name}' not found in actions list`,
108
- };
109
- }
110
- const actionArgs = action.parameters.reduce((acc, arg) => {
111
- acc[arg.name] = arg.value;
112
- return acc;
113
- }, {});
114
- console.log(`Executing ${action.name} with args:`, actionArgs);
115
- try {
116
- const result = yield actionConfig.execute(actionArgs);
117
- return {
118
- name: action.name,
119
- parameters: actionArgs,
120
- result,
121
- error: null,
122
- };
123
- }
124
- catch (error) {
125
- console.error(`Error executing action ${action.name}:`, error);
126
- return {
127
- name: action.name,
128
- parameters: actionArgs,
129
- result: null,
130
- error: error.message || "Unknown error occurred",
131
- };
132
- }
133
- });
83
+ async executeAction(action) {
84
+ // Call onActionStart callback
85
+ this.callbacks.onActionStart?.(action);
86
+ const actionConfig = this.actions.find((a) => a.name === action.name);
87
+ if (!actionConfig) {
88
+ return {
89
+ name: action.name,
90
+ parameters: {},
91
+ result: null,
92
+ error: `Action '${action.name}' not found in actions list`,
93
+ };
94
+ }
95
+ const actionArgs = action.parameters.reduce((acc, arg) => {
96
+ acc[arg.name] = arg.value;
97
+ return acc;
98
+ }, {});
99
+ try {
100
+ const result = await actionConfig.execute(actionArgs);
101
+ const actionResult = {
102
+ name: action.name,
103
+ parameters: actionArgs,
104
+ result,
105
+ error: null,
106
+ };
107
+ console.log("Action executed successfully: ", action.name);
108
+ console.dir(actionResult, { depth: null });
109
+ return actionResult;
110
+ }
111
+ catch (error) {
112
+ const actionResult = {
113
+ name: action.name,
114
+ parameters: actionArgs,
115
+ result: null,
116
+ error: error.message || "Unknown error occurred",
117
+ };
118
+ console.log("Action failed: ", action.name);
119
+ console.dir(actionResult, { depth: null });
120
+ return actionResult;
121
+ }
134
122
  }
135
123
  }
136
124
  exports.ActionQueueManager = ActionQueueManager;