@memberjunction/ai-vectors-memory 2.85.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/README.md +385 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +6 -0
- package/dist/index.js.map +1 -0
- package/dist/models/SimpleVectorService.d.ts +28 -0
- package/dist/models/SimpleVectorService.d.ts.map +1 -0
- package/dist/models/SimpleVectorService.js +119 -0
- package/dist/models/SimpleVectorService.js.map +1 -0
- package/package.json +26 -0
package/README.md
ADDED
|
@@ -0,0 +1,385 @@
|
|
|
1
|
+
# @memberjunction/ai-vectors-memory
|
|
2
|
+
|
|
3
|
+
The MemberJunction AI Vectors Memory package provides lightweight, in-memory vector similarity search capabilities without requiring external vector databases. Perfect for small to medium-sized datasets where vectors can be stored in memory.
|
|
4
|
+
|
|
5
|
+
## Overview
|
|
6
|
+
|
|
7
|
+
This package offers a simple, efficient solution for vector similarity search that is:
|
|
8
|
+
- **Storage-agnostic**: Load vectors from any source (database, files, APIs)
|
|
9
|
+
- **Zero-dependency**: No external vector database required
|
|
10
|
+
- **Fast**: Optimized in-memory cosine similarity calculations
|
|
11
|
+
- **Flexible**: Use any string identifier for your vectors
|
|
12
|
+
- **Metadata-rich**: Attach arbitrary metadata to each vector
|
|
13
|
+
|
|
14
|
+
## Installation
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
npm install @memberjunction/ai-vectors-memory
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
## Quick Start
|
|
21
|
+
|
|
22
|
+
```typescript
|
|
23
|
+
import { SimpleVectorService } from '@memberjunction/ai-vectors-memory';
|
|
24
|
+
|
|
25
|
+
// Create service instance
|
|
26
|
+
const vectorService = new SimpleVectorService();
|
|
27
|
+
|
|
28
|
+
// Load vectors with metadata
|
|
29
|
+
const entries = [
|
|
30
|
+
{
|
|
31
|
+
key: 'doc1',
|
|
32
|
+
vector: [0.1, 0.2, 0.3, 0.4],
|
|
33
|
+
metadata: { title: 'Document 1', category: 'tech' }
|
|
34
|
+
},
|
|
35
|
+
{
|
|
36
|
+
key: 'doc2',
|
|
37
|
+
vector: [0.4, 0.3, 0.2, 0.1],
|
|
38
|
+
metadata: { title: 'Document 2', category: 'science' }
|
|
39
|
+
}
|
|
40
|
+
];
|
|
41
|
+
|
|
42
|
+
vectorService.LoadVectors(entries);
|
|
43
|
+
|
|
44
|
+
// Find nearest neighbors
|
|
45
|
+
const queryVector = [0.15, 0.25, 0.35, 0.45];
|
|
46
|
+
const similar = vectorService.FindNearest(queryVector, 5);
|
|
47
|
+
|
|
48
|
+
similar.forEach(result => {
|
|
49
|
+
console.log(`${result.key}: ${result.score.toFixed(4)} - ${result.metadata.title}`);
|
|
50
|
+
});
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
## API Reference
|
|
54
|
+
|
|
55
|
+
### SimpleVectorService
|
|
56
|
+
|
|
57
|
+
The main class providing in-memory vector similarity search.
|
|
58
|
+
|
|
59
|
+
#### Methods
|
|
60
|
+
|
|
61
|
+
##### `LoadVectors(entries: VectorEntry[] | Map<string, number[]>): void`
|
|
62
|
+
Load vectors into memory. Accepts either an array of VectorEntry objects or a Map.
|
|
63
|
+
|
|
64
|
+
```typescript
|
|
65
|
+
// Load from array with metadata
|
|
66
|
+
vectorService.LoadVectors([
|
|
67
|
+
{ key: 'item1', vector: [0.1, 0.2], metadata: { name: 'Item 1' } }
|
|
68
|
+
]);
|
|
69
|
+
|
|
70
|
+
// Load from Map (without metadata)
|
|
71
|
+
const map = new Map();
|
|
72
|
+
map.set('item1', [0.1, 0.2]);
|
|
73
|
+
vectorService.LoadVectors(map);
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
##### `AddVector(key: string, vector: number[], metadata?: any): void`
|
|
77
|
+
Add or update a single vector.
|
|
78
|
+
|
|
79
|
+
```typescript
|
|
80
|
+
vectorService.AddVector('product123', [0.1, 0.2, 0.3], {
|
|
81
|
+
name: 'Product Name',
|
|
82
|
+
category: 'Electronics'
|
|
83
|
+
});
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
##### `FindNearest(queryVector: number[], topK?: number): VectorSearchResult[]`
|
|
87
|
+
Find the K nearest neighbors to a query vector using cosine similarity.
|
|
88
|
+
|
|
89
|
+
```typescript
|
|
90
|
+
const results = vectorService.FindNearest([0.1, 0.2, 0.3], 10);
|
|
91
|
+
// Returns top 10 most similar vectors
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
##### `FindSimilar(key: string, topK?: number): VectorSearchResult[]`
|
|
95
|
+
Find vectors similar to an existing vector (excludes the source vector).
|
|
96
|
+
|
|
97
|
+
```typescript
|
|
98
|
+
const similar = vectorService.FindSimilar('product123', 5);
|
|
99
|
+
// Returns 5 most similar items to product123
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
##### `Similarity(key1: string, key2: string): number`
|
|
103
|
+
Calculate cosine similarity between two vectors (returns value between -1 and 1).
|
|
104
|
+
|
|
105
|
+
```typescript
|
|
106
|
+
const score = vectorService.Similarity('item1', 'item2');
|
|
107
|
+
console.log(`Similarity: ${score}`);
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
##### `GetVector(key: string): number[] | undefined`
|
|
111
|
+
Retrieve a specific vector by its key.
|
|
112
|
+
|
|
113
|
+
```typescript
|
|
114
|
+
const vector = vectorService.GetVector('product123');
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
##### `GetMetadata(key: string): any | undefined`
|
|
118
|
+
Retrieve metadata for a specific vector.
|
|
119
|
+
|
|
120
|
+
```typescript
|
|
121
|
+
const metadata = vectorService.GetMetadata('product123');
|
|
122
|
+
console.log(metadata.name);
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
##### `RemoveVector(key: string): boolean`
|
|
126
|
+
Remove a vector from the service.
|
|
127
|
+
|
|
128
|
+
```typescript
|
|
129
|
+
const removed = vectorService.RemoveVector('product123');
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
##### `Clear(): void`
|
|
133
|
+
Clear all vectors from memory.
|
|
134
|
+
|
|
135
|
+
```typescript
|
|
136
|
+
vectorService.Clear();
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
##### `ExportVectors(): VectorEntry[]`
|
|
140
|
+
Export all vectors for persistence.
|
|
141
|
+
|
|
142
|
+
```typescript
|
|
143
|
+
const allVectors = vectorService.ExportVectors();
|
|
144
|
+
// Save to database or file
|
|
145
|
+
await saveToDatabase(allVectors);
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
##### `Size: number`
|
|
149
|
+
Get the current number of vectors (read-only property).
|
|
150
|
+
|
|
151
|
+
```typescript
|
|
152
|
+
console.log(`Total vectors: ${vectorService.Size}`);
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
##### `Has(key: string): boolean`
|
|
156
|
+
Check if a vector exists.
|
|
157
|
+
|
|
158
|
+
```typescript
|
|
159
|
+
if (vectorService.Has('product123')) {
|
|
160
|
+
console.log('Vector exists');
|
|
161
|
+
}
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
##### `GetAllKeys(): string[]`
|
|
165
|
+
Get all vector keys.
|
|
166
|
+
|
|
167
|
+
```typescript
|
|
168
|
+
const keys = vectorService.GetAllKeys();
|
|
169
|
+
console.log(`Keys: ${keys.join(', ')}`);
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
## Types
|
|
173
|
+
|
|
174
|
+
### VectorEntry
|
|
175
|
+
```typescript
|
|
176
|
+
interface VectorEntry {
|
|
177
|
+
key: string; // Unique identifier
|
|
178
|
+
vector: number[]; // Embedding array
|
|
179
|
+
metadata?: any; // Optional metadata
|
|
180
|
+
}
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
### VectorSearchResult
|
|
184
|
+
```typescript
|
|
185
|
+
interface VectorSearchResult {
|
|
186
|
+
key: string; // Vector identifier
|
|
187
|
+
score: number; // Similarity score (0-1)
|
|
188
|
+
metadata?: any; // Associated metadata
|
|
189
|
+
}
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
## Use Cases
|
|
193
|
+
|
|
194
|
+
### 1. Semantic Search with MemberJunction Entities
|
|
195
|
+
|
|
196
|
+
```typescript
|
|
197
|
+
import { SimpleVectorService } from '@memberjunction/ai-vectors-memory';
|
|
198
|
+
import { RunView } from '@memberjunction/core';
|
|
199
|
+
|
|
200
|
+
const vectorService = new SimpleVectorService();
|
|
201
|
+
const rv = new RunView();
|
|
202
|
+
|
|
203
|
+
// Load components with embeddings from database
|
|
204
|
+
const components = await rv.RunView({
|
|
205
|
+
EntityName: 'Components',
|
|
206
|
+
ResultType: 'entity_object'
|
|
207
|
+
});
|
|
208
|
+
|
|
209
|
+
// Load vectors with metadata
|
|
210
|
+
const entries = components.Results.map(comp => ({
|
|
211
|
+
key: comp.ID,
|
|
212
|
+
vector: JSON.parse(comp.EmbeddingVector),
|
|
213
|
+
metadata: {
|
|
214
|
+
name: comp.Name,
|
|
215
|
+
description: comp.Description,
|
|
216
|
+
type: comp.ComponentType
|
|
217
|
+
}
|
|
218
|
+
}));
|
|
219
|
+
|
|
220
|
+
vectorService.LoadVectors(entries);
|
|
221
|
+
|
|
222
|
+
// Search for similar components
|
|
223
|
+
const queryEmbedding = await generateEmbedding('dashboard visualization');
|
|
224
|
+
const similar = vectorService.FindNearest(queryEmbedding, 10);
|
|
225
|
+
```
|
|
226
|
+
|
|
227
|
+
### 2. Document Similarity
|
|
228
|
+
|
|
229
|
+
```typescript
|
|
230
|
+
// Load document embeddings
|
|
231
|
+
const documents = [
|
|
232
|
+
{ id: 'doc1', content: 'Machine learning basics', embedding: [...] },
|
|
233
|
+
{ id: 'doc2', content: 'Deep learning tutorial', embedding: [...] },
|
|
234
|
+
{ id: 'doc3', content: 'Neural networks guide', embedding: [...] }
|
|
235
|
+
];
|
|
236
|
+
|
|
237
|
+
const entries = documents.map(doc => ({
|
|
238
|
+
key: doc.id,
|
|
239
|
+
vector: doc.embedding,
|
|
240
|
+
metadata: { content: doc.content }
|
|
241
|
+
}));
|
|
242
|
+
|
|
243
|
+
vectorService.LoadVectors(entries);
|
|
244
|
+
|
|
245
|
+
// Find documents similar to doc1
|
|
246
|
+
const similarDocs = vectorService.FindSimilar('doc1', 2);
|
|
247
|
+
```
|
|
248
|
+
|
|
249
|
+
### 3. Product Recommendations
|
|
250
|
+
|
|
251
|
+
```typescript
|
|
252
|
+
// Load product embeddings
|
|
253
|
+
const products = await loadProductsWithEmbeddings();
|
|
254
|
+
|
|
255
|
+
vectorService.LoadVectors(
|
|
256
|
+
products.map(p => ({
|
|
257
|
+
key: p.sku,
|
|
258
|
+
vector: p.embedding,
|
|
259
|
+
metadata: {
|
|
260
|
+
name: p.name,
|
|
261
|
+
price: p.price,
|
|
262
|
+
category: p.category
|
|
263
|
+
}
|
|
264
|
+
}))
|
|
265
|
+
);
|
|
266
|
+
|
|
267
|
+
// Get recommendations for a user based on their viewed product
|
|
268
|
+
const recommendations = vectorService.FindSimilar(viewedProductSku, 10)
|
|
269
|
+
.filter(r => r.metadata.category === targetCategory)
|
|
270
|
+
.slice(0, 5);
|
|
271
|
+
```
|
|
272
|
+
|
|
273
|
+
### 4. Duplicate Detection
|
|
274
|
+
|
|
275
|
+
```typescript
|
|
276
|
+
// Check for duplicate content
|
|
277
|
+
const entries = contentItems.map(item => ({
|
|
278
|
+
key: item.id,
|
|
279
|
+
vector: item.embedding,
|
|
280
|
+
metadata: { title: item.title, createdAt: item.createdAt }
|
|
281
|
+
}));
|
|
282
|
+
|
|
283
|
+
vectorService.LoadVectors(entries);
|
|
284
|
+
|
|
285
|
+
// Find potential duplicates (high similarity threshold)
|
|
286
|
+
const potentialDuplicates = [];
|
|
287
|
+
for (const key of vectorService.GetAllKeys()) {
|
|
288
|
+
const similar = vectorService.FindSimilar(key, 5);
|
|
289
|
+
const duplicates = similar.filter(s => s.score > 0.95);
|
|
290
|
+
if (duplicates.length > 0) {
|
|
291
|
+
potentialDuplicates.push({ original: key, duplicates });
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
```
|
|
295
|
+
|
|
296
|
+
## Performance Considerations
|
|
297
|
+
|
|
298
|
+
### Memory Usage
|
|
299
|
+
- Each vector consumes approximately `4 bytes × dimensions` of memory
|
|
300
|
+
- Example: 10,000 vectors of 768 dimensions ≈ 30 MB
|
|
301
|
+
- Metadata adds additional overhead depending on content
|
|
302
|
+
|
|
303
|
+
### Computational Complexity
|
|
304
|
+
- `FindNearest`: O(n × d) where n = number of vectors, d = dimensions
|
|
305
|
+
- `AddVector`: O(1)
|
|
306
|
+
- `RemoveVector`: O(1)
|
|
307
|
+
- `Similarity`: O(d) where d = dimensions
|
|
308
|
+
|
|
309
|
+
### Recommendations
|
|
310
|
+
- **Optimal for**: < 100,000 vectors with < 1,536 dimensions
|
|
311
|
+
- **Consider alternatives**: For millions of vectors or real-time updates at scale
|
|
312
|
+
- **Batch operations**: Load all vectors at once rather than individual adds
|
|
313
|
+
- **Memory monitoring**: Monitor process memory when working with large datasets
|
|
314
|
+
|
|
315
|
+
## Integration with MemberJunction
|
|
316
|
+
|
|
317
|
+
This package integrates seamlessly with the MemberJunction ecosystem:
|
|
318
|
+
|
|
319
|
+
```typescript
|
|
320
|
+
import { SimpleVectorService } from '@memberjunction/ai-vectors-memory';
|
|
321
|
+
import { RunView } from '@memberjunction/core';
|
|
322
|
+
import { LocalEmbedding } from '@memberjunction/local-embeddings';
|
|
323
|
+
|
|
324
|
+
// Use local embeddings
|
|
325
|
+
const embedder = new LocalEmbedding();
|
|
326
|
+
const vectorService = new SimpleVectorService();
|
|
327
|
+
|
|
328
|
+
// Load entities and generate embeddings
|
|
329
|
+
const rv = new RunView();
|
|
330
|
+
const entities = await rv.RunView({
|
|
331
|
+
EntityName: 'Products',
|
|
332
|
+
ResultType: 'entity_object'
|
|
333
|
+
});
|
|
334
|
+
|
|
335
|
+
// Generate embeddings and load into service
|
|
336
|
+
const entries = await Promise.all(
|
|
337
|
+
entities.Results.map(async (entity) => ({
|
|
338
|
+
key: entity.ID,
|
|
339
|
+
vector: await embedder.EmbedText({
|
|
340
|
+
text: `${entity.Name} ${entity.Description}`,
|
|
341
|
+
model: 'all-MiniLM-L6-v2'
|
|
342
|
+
}),
|
|
343
|
+
metadata: entity.GetAll()
|
|
344
|
+
}))
|
|
345
|
+
);
|
|
346
|
+
|
|
347
|
+
vectorService.LoadVectors(entries);
|
|
348
|
+
```
|
|
349
|
+
|
|
350
|
+
## Error Handling
|
|
351
|
+
|
|
352
|
+
The service provides clear error messages:
|
|
353
|
+
|
|
354
|
+
```typescript
|
|
355
|
+
try {
|
|
356
|
+
vectorService.AddVector('', [1, 2, 3]);
|
|
357
|
+
} catch (error) {
|
|
358
|
+
// Error: Key cannot be null or undefined
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
try {
|
|
362
|
+
vectorService.FindSimilar('nonexistent');
|
|
363
|
+
} catch (error) {
|
|
364
|
+
// Error: Vector with key "nonexistent" not found
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
try {
|
|
368
|
+
vectorService.Similarity('key1', 'key2');
|
|
369
|
+
} catch (error) {
|
|
370
|
+
// Error: Vectors must have same dimensions. Got 384 and 768
|
|
371
|
+
}
|
|
372
|
+
```
|
|
373
|
+
|
|
374
|
+
## Contributing
|
|
375
|
+
|
|
376
|
+
When contributing to this package:
|
|
377
|
+
1. Follow MemberJunction coding standards
|
|
378
|
+
2. Use PascalCase for public methods and classes
|
|
379
|
+
3. Add comprehensive TypeScript types
|
|
380
|
+
4. Include JSDoc comments for public APIs
|
|
381
|
+
5. Test with various vector dimensions and sizes
|
|
382
|
+
|
|
383
|
+
## License
|
|
384
|
+
|
|
385
|
+
ISC
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAKA,OAAO,EACL,mBAAmB,EACnB,WAAW,EACX,kBAAkB,EACnB,MAAM,8BAA8B,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.SimpleVectorService = void 0;
|
|
4
|
+
var SimpleVectorService_1 = require("./models/SimpleVectorService");
|
|
5
|
+
Object.defineProperty(exports, "SimpleVectorService", { enumerable: true, get: function () { return SimpleVectorService_1.SimpleVectorService; } });
|
|
6
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAKA,oEAIsC;AAHpC,0HAAA,mBAAmB,OAAA"}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
export interface VectorEntry {
|
|
2
|
+
key: string;
|
|
3
|
+
vector: number[];
|
|
4
|
+
metadata?: any;
|
|
5
|
+
}
|
|
6
|
+
export interface VectorSearchResult {
|
|
7
|
+
key: string;
|
|
8
|
+
score: number;
|
|
9
|
+
metadata?: any;
|
|
10
|
+
}
|
|
11
|
+
export declare class SimpleVectorService {
|
|
12
|
+
private vectors;
|
|
13
|
+
LoadVectors(entries: VectorEntry[] | Map<string, number[]>): void;
|
|
14
|
+
AddVector(key: string, vector: number[], metadata?: any): void;
|
|
15
|
+
FindNearest(queryVector: number[], topK?: number): VectorSearchResult[];
|
|
16
|
+
FindSimilar(key: string, topK?: number): VectorSearchResult[];
|
|
17
|
+
Similarity(key1: string, key2: string): number;
|
|
18
|
+
protected CosineSimilarity(a: number[], b: number[]): number;
|
|
19
|
+
get Size(): number;
|
|
20
|
+
Clear(): void;
|
|
21
|
+
Has(key: string): boolean;
|
|
22
|
+
GetVector(key: string): number[] | undefined;
|
|
23
|
+
GetMetadata(key: string): any | undefined;
|
|
24
|
+
RemoveVector(key: string): boolean;
|
|
25
|
+
GetAllKeys(): string[];
|
|
26
|
+
ExportVectors(): VectorEntry[];
|
|
27
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AAS;IAqB5C,WAAW,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,GAAG,SAAS;IAoBzC,YAAY,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO;IAkBlC,UAAU,IAAI,MAAM,EAAE;IAoBtB,aAAa,IAAI,WAAW,EAAE;CAGtC"}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.SimpleVectorService = void 0;
|
|
4
|
+
const core_1 = require("@memberjunction/core");
|
|
5
|
+
class SimpleVectorService {
|
|
6
|
+
constructor() {
|
|
7
|
+
this.vectors = new Map();
|
|
8
|
+
}
|
|
9
|
+
LoadVectors(entries) {
|
|
10
|
+
if (!entries) {
|
|
11
|
+
throw new Error('Entries cannot be null or undefined');
|
|
12
|
+
}
|
|
13
|
+
if (entries instanceof Map) {
|
|
14
|
+
entries.forEach((vector, key) => {
|
|
15
|
+
this.vectors.set(key, { key, vector });
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
else {
|
|
19
|
+
entries.forEach(entry => {
|
|
20
|
+
this.vectors.set(entry.key, entry);
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
AddVector(key, vector, metadata) {
|
|
25
|
+
if (!key) {
|
|
26
|
+
throw new Error('Key cannot be null or undefined');
|
|
27
|
+
}
|
|
28
|
+
if (!vector || vector.length === 0) {
|
|
29
|
+
throw new Error('Vector cannot be null, undefined, or empty');
|
|
30
|
+
}
|
|
31
|
+
this.vectors.set(key, { key, vector, metadata });
|
|
32
|
+
}
|
|
33
|
+
FindNearest(queryVector, topK = 10) {
|
|
34
|
+
if (!queryVector || queryVector.length === 0) {
|
|
35
|
+
throw new Error('Query vector cannot be null, undefined, or empty');
|
|
36
|
+
}
|
|
37
|
+
const results = Array.from(this.vectors.values())
|
|
38
|
+
.map(entry => {
|
|
39
|
+
try {
|
|
40
|
+
return {
|
|
41
|
+
key: entry.key,
|
|
42
|
+
score: this.CosineSimilarity(queryVector, entry.vector),
|
|
43
|
+
metadata: entry.metadata
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
catch (error) {
|
|
47
|
+
(0, core_1.LogError)(`Error calculating similarity for key ${entry.key}: ${error}`);
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
})
|
|
51
|
+
.filter(result => result !== null)
|
|
52
|
+
.sort((a, b) => b.score - a.score)
|
|
53
|
+
.slice(0, topK);
|
|
54
|
+
return results;
|
|
55
|
+
}
|
|
56
|
+
FindSimilar(key, topK = 10) {
|
|
57
|
+
const sourceVector = this.vectors.get(key);
|
|
58
|
+
if (!sourceVector) {
|
|
59
|
+
throw new Error(`Vector with key "${key}" not found`);
|
|
60
|
+
}
|
|
61
|
+
return this.FindNearest(sourceVector.vector, topK + 1)
|
|
62
|
+
.filter(result => result.key !== key)
|
|
63
|
+
.slice(0, topK);
|
|
64
|
+
}
|
|
65
|
+
Similarity(key1, key2) {
|
|
66
|
+
const v1 = this.vectors.get(key1);
|
|
67
|
+
const v2 = this.vectors.get(key2);
|
|
68
|
+
if (!v1) {
|
|
69
|
+
throw new Error(`Vector with key "${key1}" not found`);
|
|
70
|
+
}
|
|
71
|
+
if (!v2) {
|
|
72
|
+
throw new Error(`Vector with key "${key2}" not found`);
|
|
73
|
+
}
|
|
74
|
+
return this.CosineSimilarity(v1.vector, v2.vector);
|
|
75
|
+
}
|
|
76
|
+
CosineSimilarity(a, b) {
|
|
77
|
+
if (a.length !== b.length) {
|
|
78
|
+
throw new Error(`Vectors must have same dimensions. Got ${a.length} and ${b.length}`);
|
|
79
|
+
}
|
|
80
|
+
let dotProduct = 0;
|
|
81
|
+
let normA = 0;
|
|
82
|
+
let normB = 0;
|
|
83
|
+
for (let i = 0; i < a.length; i++) {
|
|
84
|
+
dotProduct += a[i] * b[i];
|
|
85
|
+
normA += a[i] * a[i];
|
|
86
|
+
normB += b[i] * b[i];
|
|
87
|
+
}
|
|
88
|
+
if (normA === 0 || normB === 0) {
|
|
89
|
+
return 0;
|
|
90
|
+
}
|
|
91
|
+
return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB));
|
|
92
|
+
}
|
|
93
|
+
get Size() {
|
|
94
|
+
return this.vectors.size;
|
|
95
|
+
}
|
|
96
|
+
Clear() {
|
|
97
|
+
this.vectors.clear();
|
|
98
|
+
}
|
|
99
|
+
Has(key) {
|
|
100
|
+
return this.vectors.has(key);
|
|
101
|
+
}
|
|
102
|
+
GetVector(key) {
|
|
103
|
+
return this.vectors.get(key)?.vector;
|
|
104
|
+
}
|
|
105
|
+
GetMetadata(key) {
|
|
106
|
+
return this.vectors.get(key)?.metadata;
|
|
107
|
+
}
|
|
108
|
+
RemoveVector(key) {
|
|
109
|
+
return this.vectors.delete(key);
|
|
110
|
+
}
|
|
111
|
+
GetAllKeys() {
|
|
112
|
+
return Array.from(this.vectors.keys());
|
|
113
|
+
}
|
|
114
|
+
ExportVectors() {
|
|
115
|
+
return Array.from(this.vectors.values());
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
exports.SimpleVectorService = SimpleVectorService;
|
|
119
|
+
//# sourceMappingURL=SimpleVectorService.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"SimpleVectorService.js","sourceRoot":"","sources":["../../src/models/SimpleVectorService.ts"],"names":[],"mappings":";;;AAAA,+CAAgD;AAiDhD,MAAa,mBAAmB;IAAhC;QACU,YAAO,GAA6B,IAAI,GAAG,EAAE,CAAC;IAsaxD,CAAC;IA3YQ,WAAW,CAAC,OAA8C;QAC/D,IAAI,CAAC,OAAO,EAAE,CAAC;YACb,MAAM,IAAI,KAAK,CAAC,qCAAqC,CAAC,CAAC;QACzD,CAAC;QAED,IAAI,OAAO,YAAY,GAAG,EAAE,CAAC;YAC3B,OAAO,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,GAAG,EAAE,EAAE;gBAC9B,IAAI,CAAC,OAAO,CAAC,G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ACpB,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IAC/B,CAAC;IAmBM,SAAS,CAAC,GAAW;QAC1B,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC;IACvC,CAAC;IAmBM,WAAW,CAAC,GAAW;QAC5B,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,QAAQ,CAAC;IACzC,CAAC;IAkBM,YAAY,CAAC,GAAW;QAC7B,OAAO,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;IAClC,CAAC;IAgBM,UAAU;QACf,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC;IACzC,CAAC;IAkBM,aAAa;QAClB,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC;IAC3C,CAAC;CACF;AAvaD,kDAuaC"}
|
package/package.json
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@memberjunction/ai-vectors-memory",
|
|
3
|
+
"version": "2.85.0",
|
|
4
|
+
"description": "MemberJunction: AI Vectors In-Memory Utilities",
|
|
5
|
+
"main": "dist/index.js",
|
|
6
|
+
"types": "dist/index.d.ts",
|
|
7
|
+
"files": [
|
|
8
|
+
"/dist"
|
|
9
|
+
],
|
|
10
|
+
"scripts": {
|
|
11
|
+
"start": "ts-node-dev src/index.ts",
|
|
12
|
+
"build": "tsc",
|
|
13
|
+
"test": "echo \"Error: no test specified\" && exit 1"
|
|
14
|
+
},
|
|
15
|
+
"author": "MemberJunction.com",
|
|
16
|
+
"license": "ISC",
|
|
17
|
+
"dependencies": {
|
|
18
|
+
"@memberjunction/core": "2.85.0",
|
|
19
|
+
"@memberjunction/global": "2.85.0"
|
|
20
|
+
},
|
|
21
|
+
"devDependencies": {
|
|
22
|
+
"@types/node": "20.14.2",
|
|
23
|
+
"ts-node-dev": "^2.0.0",
|
|
24
|
+
"typescript": "^5.4.5"
|
|
25
|
+
}
|
|
26
|
+
}
|