@ai.ntellect/core 0.3.1 → 0.4.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 (86) hide show
  1. package/.nvmrc +1 -0
  2. package/README.FR.md +201 -261
  3. package/README.md +208 -260
  4. package/agent/index.ts +204 -185
  5. package/agent/tools/get-rss.ts +64 -0
  6. package/bull.ts +5 -0
  7. package/dist/agent/index.d.ts +29 -22
  8. package/dist/agent/index.js +124 -97
  9. package/dist/agent/tools/get-rss.d.ts +16 -0
  10. package/dist/agent/tools/get-rss.js +62 -0
  11. package/dist/bull.d.ts +1 -0
  12. package/dist/bull.js +9 -0
  13. package/dist/examples/index.d.ts +2 -0
  14. package/dist/examples/index.js +89 -0
  15. package/dist/llm/interpreter/context.d.ts +5 -22
  16. package/dist/llm/interpreter/context.js +8 -9
  17. package/dist/llm/interpreter/index.d.ts +9 -5
  18. package/dist/llm/interpreter/index.js +55 -48
  19. package/dist/llm/memory-manager/context.d.ts +2 -0
  20. package/dist/llm/memory-manager/context.js +22 -0
  21. package/dist/llm/memory-manager/index.d.ts +17 -0
  22. package/dist/llm/memory-manager/index.js +107 -0
  23. package/dist/llm/orchestrator/context.d.ts +2 -10
  24. package/dist/llm/orchestrator/context.js +19 -16
  25. package/dist/llm/orchestrator/index.d.ts +36 -21
  26. package/dist/llm/orchestrator/index.js +122 -88
  27. package/dist/llm/orchestrator/types.d.ts +12 -0
  28. package/dist/llm/orchestrator/types.js +2 -0
  29. package/dist/memory/cache.d.ts +6 -6
  30. package/dist/memory/cache.js +35 -42
  31. package/dist/memory/persistent.d.ts +9 -13
  32. package/dist/memory/persistent.js +94 -114
  33. package/dist/services/redis-cache.d.ts +37 -0
  34. package/dist/services/redis-cache.js +93 -0
  35. package/dist/services/scheduler.d.ts +40 -0
  36. package/dist/services/scheduler.js +99 -0
  37. package/dist/services/telegram-monitor.d.ts +0 -0
  38. package/dist/services/telegram-monitor.js +118 -0
  39. package/dist/test.d.ts +0 -167
  40. package/dist/test.js +437 -372
  41. package/dist/types.d.ts +60 -9
  42. package/dist/utils/generate-object.d.ts +12 -0
  43. package/dist/utils/generate-object.js +90 -0
  44. package/dist/utils/header-builder.d.ts +11 -0
  45. package/dist/utils/header-builder.js +34 -0
  46. package/dist/utils/inject-actions.js +2 -2
  47. package/dist/utils/queue-item-transformer.d.ts +2 -2
  48. package/dist/utils/schema-generator.d.ts +16 -0
  49. package/dist/utils/schema-generator.js +46 -0
  50. package/examples/index.ts +103 -0
  51. package/llm/interpreter/context.ts +20 -8
  52. package/llm/interpreter/index.ts +81 -54
  53. package/llm/memory-manager/context.ts +21 -0
  54. package/llm/memory-manager/index.ts +163 -0
  55. package/llm/orchestrator/context.ts +20 -13
  56. package/llm/orchestrator/index.ts +210 -130
  57. package/llm/orchestrator/types.ts +14 -0
  58. package/memory/cache.ts +41 -55
  59. package/memory/persistent.ts +121 -149
  60. package/package.json +11 -2
  61. package/services/redis-cache.ts +128 -0
  62. package/services/scheduler.ts +128 -0
  63. package/services/telegram-monitor.ts +138 -0
  64. package/t.py +79 -0
  65. package/t.spec +38 -0
  66. package/types.ts +64 -9
  67. package/utils/generate-object.ts +105 -0
  68. package/utils/header-builder.ts +40 -0
  69. package/utils/inject-actions.ts +4 -6
  70. package/utils/queue-item-transformer.ts +2 -1
  71. package/utils/schema-generator.ts +73 -0
  72. package/agent/handlers/ActionHandler.ts +0 -48
  73. package/agent/handlers/ConfirmationHandler.ts +0 -37
  74. package/agent/handlers/EventHandler.ts +0 -35
  75. package/dist/agent/handlers/ActionHandler.d.ts +0 -8
  76. package/dist/agent/handlers/ActionHandler.js +0 -36
  77. package/dist/agent/handlers/ConfirmationHandler.d.ts +0 -7
  78. package/dist/agent/handlers/ConfirmationHandler.js +0 -31
  79. package/dist/agent/handlers/EventHandler.d.ts +0 -10
  80. package/dist/agent/handlers/EventHandler.js +0 -34
  81. package/dist/llm/evaluator/context.d.ts +0 -10
  82. package/dist/llm/evaluator/context.js +0 -22
  83. package/dist/llm/evaluator/index.d.ts +0 -16
  84. package/dist/llm/evaluator/index.js +0 -151
  85. package/llm/evaluator/context.ts +0 -21
  86. package/llm/evaluator/index.ts +0 -194
package/memory/cache.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { openai } from "@ai-sdk/openai";
2
- import { cosineSimilarity, embed } from "ai";
2
+ import { cosineSimilarity, embed, EmbeddingModel } from "ai";
3
3
  import { createClient } from "redis";
4
4
  import {
5
5
  CacheMemoryOptions,
@@ -7,16 +7,16 @@ import {
7
7
  CreateMemoryInput,
8
8
  MatchOptions,
9
9
  MemoryScope,
10
- MemoryType,
11
- QueueResult,
12
10
  } from "../types";
13
11
 
14
12
  export class CacheMemory {
15
13
  private redis;
16
14
  private readonly CACHE_PREFIX: string;
17
15
  private readonly CACHE_TTL: number;
16
+ private readonly embeddingModel: EmbeddingModel<string>;
18
17
 
19
- constructor(options: CacheMemoryOptions = {}) {
18
+ constructor(options: CacheMemoryOptions) {
19
+ this.embeddingModel = options.embeddingModel;
20
20
  const ttlInHours = options.cacheTTL ?? 1;
21
21
  this.CACHE_TTL = ttlInHours * 60 * 60;
22
22
  this.CACHE_PREFIX = options.cachePrefix ?? "memory:";
@@ -44,18 +44,11 @@ export class CacheMemory {
44
44
  }
45
45
  }
46
46
 
47
- private getMemoryKey(scope: MemoryScope, userId?: string): string {
48
- if (scope === MemoryScope.GLOBAL) {
49
- return `${this.CACHE_PREFIX}global:`;
50
- }
51
- return `${this.CACHE_PREFIX}user:${userId}:`;
52
- }
53
-
54
- private async storeMemory(memory: CacheMemoryType) {
55
- const prefix = this.getMemoryKey(memory.scope, memory.userId);
47
+ private async storeMemory(memory: CacheMemoryType, ttl?: number) {
48
+ const prefix = this.CACHE_PREFIX;
56
49
  const key = `${prefix}${memory.id}`;
57
50
  const result = await this.redis.set(key, JSON.stringify(memory), {
58
- EX: this.CACHE_TTL,
51
+ EX: ttl || this.CACHE_TTL,
59
52
  });
60
53
  console.log("šŸ’¾ Cache memory created:", result);
61
54
  }
@@ -65,9 +58,9 @@ export class CacheMemory {
65
58
  options: MatchOptions & { userId?: string; scope?: MemoryScope } = {}
66
59
  ): Promise<
67
60
  {
68
- actions: QueueResult[];
69
- similarityPercentage: number;
61
+ data: any;
70
62
  query: string;
63
+ createdAt: Date;
71
64
  }[]
72
65
  > {
73
66
  console.log("\nšŸ” Searching in cache");
@@ -79,7 +72,7 @@ export class CacheMemory {
79
72
  value: query,
80
73
  });
81
74
 
82
- const memories = await this.getAllMemories(options.scope, options.userId);
75
+ const memories = await this.getAllMemories();
83
76
  console.log(`\nšŸ“š Found ${memories.length} cached queries to compare`);
84
77
 
85
78
  const matches = memories
@@ -87,7 +80,7 @@ export class CacheMemory {
87
80
  const similarity = cosineSimilarity(embedding, memory.embedding);
88
81
  const similarityPercentage = (similarity + 1) * 50;
89
82
  return {
90
- actions: memory.data,
83
+ data: memory.data,
91
84
  query: memory.query,
92
85
  similarityPercentage,
93
86
  createdAt: memory.createdAt,
@@ -110,6 +103,7 @@ export class CacheMemory {
110
103
  results.forEach((match, index) => {
111
104
  console.log(`\n${index + 1}. Match Details:`);
112
105
  console.log(` Query: ${match.query}`);
106
+ console.log(` Data: ${JSON.stringify(match.data)}`);
113
107
  console.log(` Similarity: ${match.similarityPercentage.toFixed(2)}%`);
114
108
  console.log("─".repeat(50));
115
109
  });
@@ -117,30 +111,20 @@ export class CacheMemory {
117
111
  console.log("\nāŒ No similar queries found in cache");
118
112
  }
119
113
 
120
- return results;
114
+ return results.map((match) => {
115
+ return {
116
+ data: match.data,
117
+ query: match.query,
118
+ createdAt: match.createdAt,
119
+ };
120
+ });
121
121
  }
122
122
 
123
- async getAllMemories(
124
- scope?: MemoryScope,
125
- userId?: string
126
- ): Promise<CacheMemoryType[]> {
127
- let patterns: CacheMemoryType[] = [];
128
-
129
- if (!scope || scope === MemoryScope.GLOBAL) {
130
- const globalPrefix = this.getMemoryKey(MemoryScope.GLOBAL);
131
- const globalKeys = await this.redis.keys(`${globalPrefix}*`);
132
- const globalPatterns = await this.getMemoriesFromKeys(globalKeys);
133
- patterns = patterns.concat(globalPatterns);
134
- }
123
+ async getAllMemories(): Promise<CacheMemoryType[]> {
124
+ const keys = await this.redis.keys(`${this.CACHE_PREFIX}*`);
125
+ const memories = await this.getMemoriesFromKeys(keys);
135
126
 
136
- if (userId && (!scope || scope === MemoryScope.USER)) {
137
- const userPrefix = this.getMemoryKey(MemoryScope.USER, userId);
138
- const userKeys = await this.redis.keys(`${userPrefix}*`);
139
- const userPatterns = await this.getMemoriesFromKeys(userKeys);
140
- patterns = patterns.concat(userPatterns);
141
- }
142
-
143
- return patterns;
127
+ return memories;
144
128
  }
145
129
 
146
130
  private async getMemoriesFromKeys(
@@ -160,11 +144,10 @@ export class CacheMemory {
160
144
  input: CreateMemoryInput
161
145
  ): Promise<CacheMemoryType | undefined> {
162
146
  console.log("\nšŸ“ Processing new memory creation");
163
- console.log("Content:", input.content);
164
- console.log("Type:", input.type);
165
- console.log("Scope:", input.scope);
147
+ console.log("Content:", input.query);
148
+ console.log("TTL:", input.ttl ? `${input.ttl} seconds` : "default");
166
149
 
167
- const existingPattern = await this.findSimilarActions(input.content, {
150
+ const existingPattern = await this.findSimilarActions(input.query, {
168
151
  similarityThreshold: 95,
169
152
  userId: input.userId,
170
153
  scope: input.scope,
@@ -176,7 +159,8 @@ export class CacheMemory {
176
159
  existingPattern.forEach((match, index) => {
177
160
  console.log(`\n${index + 1}. Existing Match:`);
178
161
  console.log(` Query: ${match.query}`);
179
- console.log(` Similarity: ${match.similarityPercentage.toFixed(2)}%`);
162
+ console.log(` Data: ${JSON.stringify(match.data)}`);
163
+ console.log(` Created At: ${match.createdAt}`);
180
164
  });
181
165
  console.log("\nā­ļø Skipping creation of new memory");
182
166
  return;
@@ -186,11 +170,11 @@ export class CacheMemory {
186
170
 
187
171
  const memory = await this.createSingleMemory({
188
172
  id: crypto.randomUUID(),
189
- content: input.content,
190
- type: input.type,
173
+ query: input.query,
191
174
  data: input.data,
192
175
  userId: input.userId,
193
176
  scope: input.scope,
177
+ ttl: input.ttl,
194
178
  });
195
179
 
196
180
  return memory;
@@ -198,28 +182,27 @@ export class CacheMemory {
198
182
 
199
183
  private async createSingleMemory(params: {
200
184
  id: string;
201
- content: string;
202
- type: MemoryType;
185
+ query: string;
203
186
  data: any;
204
187
  userId?: string;
205
188
  scope?: MemoryScope;
189
+ ttl?: number;
206
190
  }): Promise<CacheMemoryType> {
207
191
  console.log("\nšŸ—ļø Creating new cache memory");
208
192
  console.log("ID:", params.id);
209
- console.log("Content:", params.content);
193
+ console.log("Content:", params.query);
210
194
 
211
195
  console.log("\n🧮 Generating embedding...");
212
196
  const { embedding } = await embed({
213
- model: openai.embedding("text-embedding-3-small"),
214
- value: params.content,
197
+ model: this.embeddingModel,
198
+ value: params.query,
215
199
  });
216
200
  console.log("āœ… Embedding generated successfully");
217
201
 
218
202
  const memory: CacheMemoryType = {
219
203
  id: params.id,
220
- type: params.type,
221
204
  data: params.data,
222
- query: params.content,
205
+ query: params.query,
223
206
  embedding,
224
207
  userId: params.userId,
225
208
  scope:
@@ -227,8 +210,11 @@ export class CacheMemory {
227
210
  createdAt: new Date(),
228
211
  };
229
212
 
230
- await this.storeMemory(memory);
231
- console.log("āœ… Memory created and stored successfully");
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
+ });
232
218
 
233
219
  return memory;
234
220
  }
@@ -1,7 +1,6 @@
1
- import { openai } from "@ai-sdk/openai";
2
- import { cosineSimilarity, embed, embedMany } from "ai";
1
+ import { cosineSimilarity, embed, EmbeddingModel, embedMany } from "ai";
3
2
  import { RecursiveCharacterTextSplitter } from "langchain/text_splitter";
4
- import { Memory, MemoryScope } from "../types";
3
+ import { LongTermMemory, MemoryScope } from "../types";
5
4
 
6
5
  interface SearchOptions {
7
6
  scope?: MemoryScope;
@@ -28,18 +27,6 @@ interface MeilisearchResponse {
28
27
  }>;
29
28
  }
30
29
 
31
- interface SearchParams {
32
- q?: string;
33
- offset?: number;
34
- limit?: number;
35
- filter?: string | string[];
36
- facets?: string[];
37
- attributesToRetrieve?: string[];
38
- attributesToSearchOn?: string[];
39
- sort?: string[];
40
- matchingStrategy?: "last" | "all" | "frequency";
41
- }
42
-
43
30
  interface ProcessedChunk {
44
31
  content: string;
45
32
  embedding: number[];
@@ -52,22 +39,31 @@ export class PersistentMemory {
52
39
  private readonly host: string;
53
40
  private readonly apiKey: string;
54
41
  private readonly INDEX_PREFIX: string;
55
-
56
- constructor(options: { host: string; apiKey: string; indexPrefix?: string }) {
42
+ private readonly embeddingModel: EmbeddingModel<string>;
43
+ constructor(options: {
44
+ host: string;
45
+ apiKey: string;
46
+ indexPrefix?: string;
47
+ embeddingModel: EmbeddingModel<string>;
48
+ }) {
57
49
  this.host = options.host;
58
50
  this.apiKey = options.apiKey;
59
- this.INDEX_PREFIX = options.indexPrefix || "memory_";
51
+ this.INDEX_PREFIX = options.indexPrefix || "memory";
52
+ this.embeddingModel = options.embeddingModel;
60
53
  }
61
54
 
62
55
  /**
63
56
  * Initialize indexes
64
57
  */
65
58
  async init() {
66
- // Create global index
67
- await this._getOrCreateIndex(this._getIndexName(MemoryScope.GLOBAL));
68
-
69
- // Create user index
70
- await this._getOrCreateIndex(this._getIndexName(MemoryScope.USER));
59
+ try {
60
+ // Create or get main index
61
+ await this._getOrCreateIndex(this.INDEX_PREFIX);
62
+ console.log(`āœ… Index '${this.INDEX_PREFIX}' initialized successfully`);
63
+ } catch (error) {
64
+ console.error(`āŒ Failed to initialize index: ${error}`);
65
+ throw error;
66
+ }
71
67
  }
72
68
 
73
69
  /**
@@ -78,6 +74,7 @@ export class PersistentMemory {
78
74
  options: RequestInit = {}
79
75
  ): Promise<T> {
80
76
  const url = `${this.host}${path}`;
77
+ console.log("šŸ” Making request to Meilisearch:", url);
81
78
  const response = await fetch(url, {
82
79
  ...options,
83
80
  headers: {
@@ -95,29 +92,26 @@ export class PersistentMemory {
95
92
  return response.json() as Promise<T>;
96
93
  }
97
94
 
98
- /**
99
- * Get index name based on scope and userId
100
- */
101
- private _getIndexName(scope: MemoryScope, userId?: string): string {
102
- if (scope === "global") {
103
- return `${this.INDEX_PREFIX}global`;
104
- }
105
- return `${this.INDEX_PREFIX}user_${userId}`;
106
- }
107
-
108
95
  /**
109
96
  * Get or create an index with proper settings
110
97
  */
111
98
  private async _getOrCreateIndex(indexName: string) {
112
99
  try {
113
- // Try to create index
114
- await this._makeRequest("/indexes", {
115
- method: "POST",
116
- body: JSON.stringify({
117
- uid: indexName,
118
- primaryKey: "id",
119
- }),
120
- });
100
+ // Check if index exists first
101
+ const indexExists = await this._makeRequest(`/indexes/${indexName}`, {
102
+ method: "GET",
103
+ }).catch(() => false);
104
+
105
+ if (!indexExists) {
106
+ console.log(`Creating new index: ${indexName}`);
107
+ await this._makeRequest("/indexes", {
108
+ method: "POST",
109
+ body: JSON.stringify({
110
+ uid: indexName,
111
+ primaryKey: "id",
112
+ }),
113
+ });
114
+ }
121
115
 
122
116
  // Update index settings
123
117
  const settings: MeilisearchSettings = {
@@ -129,11 +123,11 @@ export class PersistentMemory {
129
123
  method: "PATCH",
130
124
  body: JSON.stringify(settings),
131
125
  });
126
+
127
+ console.log(`Index ${indexName} configured successfully`);
132
128
  } catch (error: any) {
133
- // Index might already exist, which is fine
134
- if (!error.message.includes("already exists")) {
135
- throw error;
136
- }
129
+ console.error(`Failed to configure index ${indexName}:`, error);
130
+ throw error;
137
131
  }
138
132
  }
139
133
 
@@ -146,7 +140,7 @@ export class PersistentMemory {
146
140
 
147
141
  // Generate embeddings for all chunks
148
142
  const { embeddings } = await embedMany({
149
- model: openai.embedding("text-embedding-3-small"),
143
+ model: this.embeddingModel,
150
144
  values: chunks.map((chunk) => chunk.pageContent),
151
145
  });
152
146
 
@@ -160,133 +154,111 @@ export class PersistentMemory {
160
154
  /**
161
155
  * Store a memory in the database
162
156
  */
163
- async createMemory(memory: Memory) {
164
- const indexName = this._getIndexName(memory.scope, memory.userId);
165
- await this._getOrCreateIndex(indexName);
157
+ async createMemory(memory: LongTermMemory) {
158
+ try {
159
+ console.log(`šŸ“ Creating memory in index: ${this.INDEX_PREFIX}`);
166
160
 
167
- const chunks = await this.processContent(memory.data);
161
+ // Process content into chunks with embeddings
162
+ const chunks = await this.processContent(memory.data);
168
163
 
169
- const document = {
170
- ...memory,
171
- chunks,
172
- createdAt: memory.createdAt.toISOString(),
173
- };
164
+ // Generate unique ID if not provided
165
+ const id = memory.id || crypto.randomUUID();
174
166
 
175
- const response = await this._makeRequest(
176
- `/indexes/${indexName}/documents`,
177
- {
178
- method: "POST",
179
- body: JSON.stringify([document]),
180
- }
181
- );
182
- console.log("Stored persistent memory response:", response);
183
- return response;
167
+ const document = {
168
+ ...memory,
169
+ chunks,
170
+ createdAt: memory.createdAt.toISOString(),
171
+ };
172
+
173
+ const response = await this._makeRequest(
174
+ `/indexes/${this.INDEX_PREFIX}/documents`,
175
+ {
176
+ method: "POST",
177
+ body: JSON.stringify([document]),
178
+ }
179
+ );
180
+
181
+ console.log("āœ… Memory created successfully", { id });
182
+ return response;
183
+ } catch (error) {
184
+ console.error("āŒ Failed to create memory:", error);
185
+ throw error;
186
+ }
184
187
  }
185
188
 
186
189
  /**
187
190
  * Find best matching memories
188
191
  */
189
192
  async findRelevantDocuments(query: string, options: SearchOptions = {}) {
190
- console.log("\nšŸ” Searching in persistent memory");
193
+ console.log(`\nšŸ” Searching in index: ${this.INDEX_PREFIX}`);
191
194
  console.log("Query:", query);
192
- console.log("Options:", JSON.stringify(options, null, 2));
193
195
 
194
- // Generate embedding for the query
195
- const { embedding: queryEmbedding } = await embed({
196
- model: openai.embedding("text-embedding-3-small"),
197
- value: query,
198
- });
199
-
200
- const searchResults = [];
201
-
202
- // Search in global memories
203
- if (!options.scope || options.scope === "global") {
204
- const globalIndex = this._getIndexName(MemoryScope.GLOBAL);
205
- console.log("\nšŸ“š Searching in global index:", globalIndex);
206
- try {
207
- const globalResults = await this._makeRequest<MeilisearchResponse>(
208
- `/indexes/${globalIndex}/search`,
209
- {
210
- method: "POST",
211
- body: JSON.stringify({ q: query }),
212
- }
213
- );
214
- if (globalResults?.hits) {
215
- searchResults.push(...globalResults.hits);
216
- }
217
- } catch (error) {
218
- console.error("āŒ Error searching global index:", error);
219
- }
220
- }
196
+ try {
197
+ // Generate embedding for the query
198
+ const { embedding: queryEmbedding } = await embed({
199
+ model: this.embeddingModel,
200
+ value: query,
201
+ });
221
202
 
222
- // Search in user memories
223
- if (
224
- options.userId &&
225
- (!options.scope || options.scope === MemoryScope.USER)
226
- ) {
227
- const userIndex = this._getIndexName(MemoryScope.USER, options.userId);
228
- const userResults = await this._makeRequest<MeilisearchResponse>(
229
- `/indexes/${userIndex}/search`,
203
+ // Search in the index
204
+ const searchResults = await this._makeRequest<MeilisearchResponse>(
205
+ `/indexes/${this.INDEX_PREFIX}/search`,
230
206
  {
231
207
  method: "POST",
232
- body: JSON.stringify({ q: query }),
208
+ body: JSON.stringify({
209
+ q: query,
210
+ limit: options.maxResults || 10,
211
+ }),
233
212
  }
234
213
  );
235
- if (userResults.hits) {
236
- searchResults.push(...userResults.hits);
237
- }
238
- }
239
-
240
- const totalResults = searchResults.length;
241
- console.log(`\nšŸ“Š Found ${totalResults} total matches`);
242
214
 
243
- // Process and filter results using cosine similarity
244
- const results = searchResults
245
- .flatMap((hit) => {
246
- const chunkSimilarities = hit.chunks.map((chunk) => ({
247
- query: hit.query,
248
- data: hit.data,
249
- similarityPercentage:
250
- (cosineSimilarity(queryEmbedding, chunk.embedding) + 1) * 50,
251
- createdAt: hit.createdAt,
252
- }));
253
-
254
- return chunkSimilarities.reduce(
255
- (best, current) =>
256
- current.similarityPercentage > best.similarityPercentage
257
- ? current
258
- : best,
259
- chunkSimilarities[0]
260
- );
261
- })
262
- .filter(
263
- (match) =>
264
- match.similarityPercentage >= (options.similarityThreshold || 70)
265
- )
266
- .sort((a, b) => b.similarityPercentage - a.similarityPercentage);
267
-
268
- // Log filtered results in a more structured way
269
- if (results.length > 0) {
270
- console.log("\n✨ Relevant matches found:");
271
- console.log("─".repeat(50));
215
+ if (!searchResults?.hits?.length) {
216
+ console.log("āŒ No matches found");
217
+ return [];
218
+ }
272
219
 
273
- results.forEach((match, index) => {
274
- console.log(`\n${index + 1}. Match Details:`);
275
- console.log(` Query: ${match.query}`);
276
- });
277
- } else {
278
- console.log("\nāŒ No relevant matches found");
220
+ // Process and filter results using cosine similarity
221
+ const results = searchResults.hits
222
+ .flatMap((hit) => {
223
+ const chunkSimilarities = hit.chunks.map((chunk) => ({
224
+ query: hit.query,
225
+ data: hit.data,
226
+ similarityPercentage:
227
+ (cosineSimilarity(queryEmbedding, chunk.embedding) + 1) * 50,
228
+ createdAt: hit.createdAt,
229
+ }));
230
+
231
+ return chunkSimilarities.reduce(
232
+ (best, current) =>
233
+ current.similarityPercentage > best.similarityPercentage
234
+ ? current
235
+ : best,
236
+ chunkSimilarities[0]
237
+ );
238
+ })
239
+ .filter(
240
+ (match) =>
241
+ match.similarityPercentage >= (options.similarityThreshold || 70)
242
+ )
243
+ .sort((a, b) => b.similarityPercentage - a.similarityPercentage);
244
+
245
+ console.log(`✨ Found ${results.length} relevant matches`);
246
+ return results.map((result) => ({
247
+ query: result.query,
248
+ data: result.data,
249
+ createdAt: result.createdAt,
250
+ }));
251
+ } catch (error) {
252
+ console.error("āŒ Search failed:", error);
253
+ return [];
279
254
  }
280
-
281
- return results;
282
255
  }
283
256
 
284
257
  /**
285
258
  * Delete memories for a given scope and user
286
259
  */
287
- async deleteMemories(scope: MemoryScope, userId?: string) {
288
- const indexName = this._getIndexName(scope, userId);
289
- return this._makeRequest(`/indexes/${indexName}`, {
260
+ async deleteMemories() {
261
+ return this._makeRequest(`/indexes/${this.INDEX_PREFIX}`, {
290
262
  method: "DELETE",
291
263
  });
292
264
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ai.ntellect/core",
3
- "version": "0.3.1",
3
+ "version": "0.4.0",
4
4
  "description": "",
5
5
  "main": "dist/index.js",
6
6
  "scripts": {
@@ -12,18 +12,24 @@
12
12
  "author": "Lorcann Rauzduel",
13
13
  "license": "ISC",
14
14
  "dependencies": {
15
+ "@ai-sdk/deepseek": "^0.1.0",
15
16
  "@ai-sdk/openai": "1.0.6",
17
+ "@types/node-cron": "^3.0.11",
16
18
  "ai": "^3.0.0",
17
19
  "ethers": "^6.13.5",
18
20
  "langchain": "^0.3.11",
21
+ "node-cron": "^3.0.3",
22
+ "readline": "^1.3.0",
19
23
  "redis": "^4.7.0",
20
24
  "rss-parser": "^3.13.0",
25
+ "ws": "^8.18.0",
21
26
  "zod": "^3.24.1"
22
27
  },
23
28
  "devDependencies": {
24
29
  "@jest/globals": "^29.7.0",
25
30
  "@types/chai": "^4.3.20",
26
31
  "@types/mocha": "^10.0.0",
32
+ "@types/ws": "^8.5.14",
27
33
  "chai": "^4.5.0",
28
34
  "mocha": "^10.0.0",
29
35
  "ts-node": "^10.9.0",
@@ -37,5 +43,8 @@
37
43
  "bugs": {
38
44
  "url": "https://github.com/ai-ntellect/core/issues"
39
45
  },
40
- "homepage": "https://github.com/ai-ntellect/core#readme"
46
+ "homepage": "https://github.com/ai-ntellect/core#readme",
47
+ "bin": {
48
+ "wallet-assistant": "./dist/examples/index.js"
49
+ }
41
50
  }