@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.
- package/.nvmrc +1 -0
- package/README.FR.md +201 -261
- package/README.md +208 -260
- package/agent/index.ts +204 -185
- package/agent/tools/get-rss.ts +64 -0
- package/bull.ts +5 -0
- package/dist/agent/index.d.ts +29 -22
- package/dist/agent/index.js +124 -97
- package/dist/agent/tools/get-rss.d.ts +16 -0
- package/dist/agent/tools/get-rss.js +62 -0
- package/dist/bull.d.ts +1 -0
- package/dist/bull.js +9 -0
- package/dist/examples/index.d.ts +2 -0
- package/dist/examples/index.js +89 -0
- package/dist/llm/interpreter/context.d.ts +5 -22
- package/dist/llm/interpreter/context.js +8 -9
- package/dist/llm/interpreter/index.d.ts +9 -5
- package/dist/llm/interpreter/index.js +55 -48
- package/dist/llm/memory-manager/context.d.ts +2 -0
- package/dist/llm/memory-manager/context.js +22 -0
- package/dist/llm/memory-manager/index.d.ts +17 -0
- package/dist/llm/memory-manager/index.js +107 -0
- package/dist/llm/orchestrator/context.d.ts +2 -10
- package/dist/llm/orchestrator/context.js +19 -16
- package/dist/llm/orchestrator/index.d.ts +36 -21
- package/dist/llm/orchestrator/index.js +122 -88
- package/dist/llm/orchestrator/types.d.ts +12 -0
- package/dist/llm/orchestrator/types.js +2 -0
- package/dist/memory/cache.d.ts +6 -6
- package/dist/memory/cache.js +35 -42
- package/dist/memory/persistent.d.ts +9 -13
- package/dist/memory/persistent.js +94 -114
- package/dist/services/redis-cache.d.ts +37 -0
- package/dist/services/redis-cache.js +93 -0
- package/dist/services/scheduler.d.ts +40 -0
- package/dist/services/scheduler.js +99 -0
- package/dist/services/telegram-monitor.d.ts +0 -0
- package/dist/services/telegram-monitor.js +118 -0
- package/dist/test.d.ts +0 -167
- package/dist/test.js +437 -372
- package/dist/types.d.ts +60 -9
- package/dist/utils/generate-object.d.ts +12 -0
- package/dist/utils/generate-object.js +90 -0
- package/dist/utils/header-builder.d.ts +11 -0
- package/dist/utils/header-builder.js +34 -0
- package/dist/utils/inject-actions.js +2 -2
- package/dist/utils/queue-item-transformer.d.ts +2 -2
- package/dist/utils/schema-generator.d.ts +16 -0
- package/dist/utils/schema-generator.js +46 -0
- package/examples/index.ts +103 -0
- package/llm/interpreter/context.ts +20 -8
- package/llm/interpreter/index.ts +81 -54
- package/llm/memory-manager/context.ts +21 -0
- package/llm/memory-manager/index.ts +163 -0
- package/llm/orchestrator/context.ts +20 -13
- package/llm/orchestrator/index.ts +210 -130
- package/llm/orchestrator/types.ts +14 -0
- package/memory/cache.ts +41 -55
- package/memory/persistent.ts +121 -149
- package/package.json +11 -2
- package/services/redis-cache.ts +128 -0
- package/services/scheduler.ts +128 -0
- package/services/telegram-monitor.ts +138 -0
- package/t.py +79 -0
- package/t.spec +38 -0
- package/types.ts +64 -9
- package/utils/generate-object.ts +105 -0
- package/utils/header-builder.ts +40 -0
- package/utils/inject-actions.ts +4 -6
- package/utils/queue-item-transformer.ts +2 -1
- package/utils/schema-generator.ts +73 -0
- package/agent/handlers/ActionHandler.ts +0 -48
- package/agent/handlers/ConfirmationHandler.ts +0 -37
- package/agent/handlers/EventHandler.ts +0 -35
- package/dist/agent/handlers/ActionHandler.d.ts +0 -8
- package/dist/agent/handlers/ActionHandler.js +0 -36
- package/dist/agent/handlers/ConfirmationHandler.d.ts +0 -7
- package/dist/agent/handlers/ConfirmationHandler.js +0 -31
- package/dist/agent/handlers/EventHandler.d.ts +0 -10
- package/dist/agent/handlers/EventHandler.js +0 -34
- package/dist/llm/evaluator/context.d.ts +0 -10
- package/dist/llm/evaluator/context.js +0 -22
- package/dist/llm/evaluator/index.d.ts +0 -16
- package/dist/llm/evaluator/index.js +0 -151
- package/llm/evaluator/context.ts +0 -21
- 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
|
48
|
-
|
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
|
-
|
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(
|
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
|
-
|
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
|
-
|
125
|
-
|
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
|
-
|
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.
|
164
|
-
console.log("
|
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.
|
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(`
|
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
|
-
|
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
|
-
|
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.
|
193
|
+
console.log("Content:", params.query);
|
210
194
|
|
211
195
|
console.log("\nš§® Generating embedding...");
|
212
196
|
const { embedding } = await embed({
|
213
|
-
model:
|
214
|
-
value: params.
|
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.
|
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("ā
|
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
|
}
|
package/memory/persistent.ts
CHANGED
@@ -1,7 +1,6 @@
|
|
1
|
-
import {
|
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 {
|
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: {
|
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 || "
|
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
|
-
|
67
|
-
|
68
|
-
|
69
|
-
|
70
|
-
|
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
|
-
//
|
114
|
-
await this._makeRequest(
|
115
|
-
method: "
|
116
|
-
|
117
|
-
|
118
|
-
|
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
|
-
|
134
|
-
|
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:
|
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:
|
164
|
-
|
165
|
-
|
157
|
+
async createMemory(memory: LongTermMemory) {
|
158
|
+
try {
|
159
|
+
console.log(`š Creating memory in index: ${this.INDEX_PREFIX}`);
|
166
160
|
|
167
|
-
|
161
|
+
// Process content into chunks with embeddings
|
162
|
+
const chunks = await this.processContent(memory.data);
|
168
163
|
|
169
|
-
|
170
|
-
|
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
|
-
|
176
|
-
|
177
|
-
|
178
|
-
|
179
|
-
|
180
|
-
|
181
|
-
|
182
|
-
|
183
|
-
|
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(
|
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
|
-
|
195
|
-
|
196
|
-
|
197
|
-
|
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
|
-
|
223
|
-
|
224
|
-
|
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({
|
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
|
-
|
244
|
-
|
245
|
-
|
246
|
-
|
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
|
274
|
-
|
275
|
-
|
276
|
-
|
277
|
-
|
278
|
-
|
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(
|
288
|
-
|
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
|
+
"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
|
}
|