@soulcraft/brainy 3.13.0 → 3.14.1
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 +41 -30
- package/dist/brainy.d.ts +567 -3
- package/dist/brainy.js +567 -3
- package/dist/config/sharedConfigManager.js +2 -1
- package/dist/types/augmentations.d.ts +138 -0
- package/dist/types/augmentations.js +12 -0
- package/dist/utils/version.js +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -209,54 +209,65 @@ await brain.find("Popular JavaScript libraries similar to Vue")
|
|
|
209
209
|
await brain.find("Documentation about authentication from last month")
|
|
210
210
|
```
|
|
211
211
|
|
|
212
|
-
### 🧠🌐 **
|
|
212
|
+
### 🧠🌐 **Virtual Filesystem - Intelligent File Management**
|
|
213
213
|
|
|
214
|
-
**
|
|
214
|
+
**Build file explorers, IDEs, and knowledge systems that never crash from infinite recursion.**
|
|
215
215
|
|
|
216
|
-
- **
|
|
217
|
-
- **
|
|
218
|
-
- **
|
|
219
|
-
- **
|
|
220
|
-
- **Perfect Memory**: Every piece of knowledge remembers its entire history
|
|
221
|
-
- **Knowledge Evolution**: Watch ideas grow and connect across time and projects
|
|
216
|
+
- **Tree-Aware Operations**: Safe directory listing prevents recursive loops
|
|
217
|
+
- **Semantic Search**: Find files by content, not just filename
|
|
218
|
+
- **Production Storage**: Filesystem and cloud storage for real applications
|
|
219
|
+
- **Zero-Config**: Works out of the box with intelligent defaults
|
|
222
220
|
|
|
223
221
|
```javascript
|
|
224
222
|
import { Brainy } from '@soulcraft/brainy'
|
|
225
223
|
|
|
226
|
-
|
|
224
|
+
// ✅ CORRECT: Use persistent storage for file systems
|
|
225
|
+
const brain = new Brainy({
|
|
226
|
+
storage: {
|
|
227
|
+
type: 'filesystem', // Persisted to disk
|
|
228
|
+
path: './brainy-data' // Your file storage
|
|
229
|
+
}
|
|
230
|
+
})
|
|
227
231
|
await brain.init()
|
|
232
|
+
|
|
228
233
|
const vfs = brain.vfs()
|
|
229
234
|
await vfs.init()
|
|
230
235
|
|
|
231
|
-
//
|
|
232
|
-
await vfs.writeFile('/
|
|
236
|
+
// ✅ Safe file operations
|
|
237
|
+
await vfs.writeFile('/projects/app/index.js', 'console.log("Hello")')
|
|
238
|
+
await vfs.mkdir('/docs')
|
|
239
|
+
await vfs.writeFile('/docs/README.md', '# My Project')
|
|
233
240
|
|
|
234
|
-
//
|
|
235
|
-
const
|
|
236
|
-
|
|
237
|
-
type: 'character',
|
|
238
|
-
description: 'Brave explorer discovering quantum worlds'
|
|
239
|
-
})
|
|
241
|
+
// ✅ NEVER crashes: Tree-aware directory listing
|
|
242
|
+
const children = await vfs.getDirectChildren('/projects')
|
|
243
|
+
// Returns only direct children, never the directory itself
|
|
240
244
|
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
+
// ✅ Build file explorers safely
|
|
246
|
+
const tree = await vfs.getTreeStructure('/projects', {
|
|
247
|
+
maxDepth: 3, // Prevent deep recursion
|
|
248
|
+
sort: 'name' // Organized results
|
|
245
249
|
})
|
|
246
250
|
|
|
247
|
-
//
|
|
248
|
-
await vfs.
|
|
249
|
-
await vfs.
|
|
251
|
+
// ✅ Semantic file search
|
|
252
|
+
const reactFiles = await vfs.search('React components with hooks')
|
|
253
|
+
const docs = await vfs.search('API documentation', {
|
|
254
|
+
path: '/docs' // Search within specific directory
|
|
255
|
+
})
|
|
250
256
|
|
|
251
|
-
//
|
|
252
|
-
|
|
253
|
-
// Returns: files, entities, concepts, relationships - ALL knowledge
|
|
257
|
+
// ✅ Connect related files
|
|
258
|
+
await vfs.addRelationship('/src/auth.js', '/tests/auth.test.js', 'tested-by')
|
|
254
259
|
|
|
255
|
-
//
|
|
256
|
-
const aliceKnowledge = await vfs.getEntityGraph(alice)
|
|
257
|
-
// Her relationships, appearances, evolution - her entire existence
|
|
260
|
+
// Perfect for: File explorers, IDEs, documentation systems, code analysis
|
|
258
261
|
```
|
|
259
262
|
|
|
263
|
+
**🚨 Prevents Common Mistakes:**
|
|
264
|
+
- ❌ No infinite recursion in file trees (like brain-cloud team experienced)
|
|
265
|
+
- ❌ No data loss from memory storage
|
|
266
|
+
- ❌ No performance issues with large directories
|
|
267
|
+
- ❌ No need for complex fallback patterns
|
|
268
|
+
|
|
269
|
+
**[📖 VFS Quick Start →](docs/vfs/QUICK_START.md)** | **[🎯 Common Patterns →](docs/vfs/COMMON_PATTERNS.md)**
|
|
270
|
+
|
|
260
271
|
**Your knowledge isn't trapped anymore.** Characters live beyond stories. APIs exist beyond code files. Concepts connect across domains. This is knowledge that happens to support files, not a filesystem that happens to store knowledge.
|
|
261
272
|
|
|
262
273
|
### 🎯 Zero Configuration Philosophy
|
package/dist/brainy.d.ts
CHANGED
|
@@ -56,10 +56,122 @@ export declare class Brainy<T = any> implements BrainyInterface<T> {
|
|
|
56
56
|
get isInitialized(): boolean;
|
|
57
57
|
/**
|
|
58
58
|
* Add an entity to the database
|
|
59
|
+
*
|
|
60
|
+
* @param params - Parameters for adding the entity
|
|
61
|
+
* @returns Promise that resolves to the entity ID
|
|
62
|
+
*
|
|
63
|
+
* @example Basic entity creation
|
|
64
|
+
* ```typescript
|
|
65
|
+
* const id = await brain.add({
|
|
66
|
+
* data: "John Smith is a software engineer",
|
|
67
|
+
* type: NounType.Person,
|
|
68
|
+
* metadata: { role: "engineer", team: "backend" }
|
|
69
|
+
* })
|
|
70
|
+
* console.log(`Created entity: ${id}`)
|
|
71
|
+
* ```
|
|
72
|
+
*
|
|
73
|
+
* @example Adding with custom ID
|
|
74
|
+
* ```typescript
|
|
75
|
+
* const customId = await brain.add({
|
|
76
|
+
* id: "user-12345",
|
|
77
|
+
* data: "Important document content",
|
|
78
|
+
* type: NounType.Document,
|
|
79
|
+
* metadata: { priority: "high", department: "legal" }
|
|
80
|
+
* })
|
|
81
|
+
* ```
|
|
82
|
+
*
|
|
83
|
+
* @example Using pre-computed vector (optimization)
|
|
84
|
+
* ```typescript
|
|
85
|
+
* const vector = await brain.embed("Optimized content")
|
|
86
|
+
* const id = await brain.add({
|
|
87
|
+
* data: "Optimized content",
|
|
88
|
+
* type: NounType.Document,
|
|
89
|
+
* vector: vector, // Skip re-embedding
|
|
90
|
+
* metadata: { optimized: true }
|
|
91
|
+
* })
|
|
92
|
+
* ```
|
|
93
|
+
*
|
|
94
|
+
* @example Multi-tenant usage
|
|
95
|
+
* ```typescript
|
|
96
|
+
* const id = await brain.add({
|
|
97
|
+
* data: "Customer feedback",
|
|
98
|
+
* type: NounType.Message,
|
|
99
|
+
* service: "customer-portal", // Multi-tenancy
|
|
100
|
+
* metadata: { rating: 5, verified: true }
|
|
101
|
+
* })
|
|
102
|
+
* ```
|
|
59
103
|
*/
|
|
60
104
|
add(params: AddParams<T>): Promise<string>;
|
|
61
105
|
/**
|
|
62
106
|
* Get an entity by ID
|
|
107
|
+
*
|
|
108
|
+
* @param id - The unique identifier of the entity to retrieve
|
|
109
|
+
* @returns Promise that resolves to the entity if found, null if not found
|
|
110
|
+
*
|
|
111
|
+
* @example
|
|
112
|
+
* // Basic entity retrieval
|
|
113
|
+
* const entity = await brainy.get('user-123')
|
|
114
|
+
* if (entity) {
|
|
115
|
+
* console.log('Found entity:', entity.data)
|
|
116
|
+
* console.log('Created at:', new Date(entity.createdAt))
|
|
117
|
+
* } else {
|
|
118
|
+
* console.log('Entity not found')
|
|
119
|
+
* }
|
|
120
|
+
*
|
|
121
|
+
* @example
|
|
122
|
+
* // Working with typed entities
|
|
123
|
+
* interface User {
|
|
124
|
+
* name: string
|
|
125
|
+
* email: string
|
|
126
|
+
* }
|
|
127
|
+
*
|
|
128
|
+
* const brainy = new Brainy<User>({ storage: 'filesystem' })
|
|
129
|
+
* const user = await brainy.get('user-456')
|
|
130
|
+
* if (user) {
|
|
131
|
+
* // TypeScript knows user.metadata is of type User
|
|
132
|
+
* console.log(`Hello ${user.metadata.name}`)
|
|
133
|
+
* }
|
|
134
|
+
*
|
|
135
|
+
* @example
|
|
136
|
+
* // Safe retrieval with error handling
|
|
137
|
+
* try {
|
|
138
|
+
* const entity = await brainy.get('document-789')
|
|
139
|
+
* if (!entity) {
|
|
140
|
+
* throw new Error('Document not found')
|
|
141
|
+
* }
|
|
142
|
+
*
|
|
143
|
+
* // Process the entity
|
|
144
|
+
* return {
|
|
145
|
+
* id: entity.id,
|
|
146
|
+
* content: entity.data,
|
|
147
|
+
* type: entity.type,
|
|
148
|
+
* metadata: entity.metadata
|
|
149
|
+
* }
|
|
150
|
+
* } catch (error) {
|
|
151
|
+
* console.error('Failed to retrieve entity:', error)
|
|
152
|
+
* return null
|
|
153
|
+
* }
|
|
154
|
+
*
|
|
155
|
+
* @example
|
|
156
|
+
* // Batch retrieval pattern
|
|
157
|
+
* const ids = ['doc-1', 'doc-2', 'doc-3']
|
|
158
|
+
* const entities = await Promise.all(
|
|
159
|
+
* ids.map(id => brainy.get(id))
|
|
160
|
+
* )
|
|
161
|
+
* const foundEntities = entities.filter(entity => entity !== null)
|
|
162
|
+
* console.log(`Found ${foundEntities.length} out of ${ids.length} entities`)
|
|
163
|
+
*
|
|
164
|
+
* @example
|
|
165
|
+
* // Using with async iteration
|
|
166
|
+
* const entityIds = ['user-1', 'user-2', 'user-3']
|
|
167
|
+
*
|
|
168
|
+
* for (const id of entityIds) {
|
|
169
|
+
* const entity = await brainy.get(id)
|
|
170
|
+
* if (entity) {
|
|
171
|
+
* console.log(`Processing ${entity.type}: ${id}`)
|
|
172
|
+
* // Process entity...
|
|
173
|
+
* }
|
|
174
|
+
* }
|
|
63
175
|
*/
|
|
64
176
|
get(id: string): Promise<Entity<T> | null>;
|
|
65
177
|
/**
|
|
@@ -76,6 +188,107 @@ export declare class Brainy<T = any> implements BrainyInterface<T> {
|
|
|
76
188
|
delete(id: string): Promise<void>;
|
|
77
189
|
/**
|
|
78
190
|
* Create a relationship between entities
|
|
191
|
+
*
|
|
192
|
+
* @param params - Parameters for creating the relationship
|
|
193
|
+
* @returns Promise that resolves to the relationship ID
|
|
194
|
+
*
|
|
195
|
+
* @example
|
|
196
|
+
* // Basic relationship creation
|
|
197
|
+
* const userId = await brainy.add({
|
|
198
|
+
* data: { name: 'John', role: 'developer' },
|
|
199
|
+
* type: NounType.Person
|
|
200
|
+
* })
|
|
201
|
+
* const projectId = await brainy.add({
|
|
202
|
+
* data: { name: 'AI Assistant', status: 'active' },
|
|
203
|
+
* type: NounType.Thing
|
|
204
|
+
* })
|
|
205
|
+
*
|
|
206
|
+
* const relationId = await brainy.relate({
|
|
207
|
+
* from: userId,
|
|
208
|
+
* to: projectId,
|
|
209
|
+
* type: VerbType.WorksOn
|
|
210
|
+
* })
|
|
211
|
+
*
|
|
212
|
+
* @example
|
|
213
|
+
* // Bidirectional relationships
|
|
214
|
+
* const friendshipId = await brainy.relate({
|
|
215
|
+
* from: 'user-1',
|
|
216
|
+
* to: 'user-2',
|
|
217
|
+
* type: VerbType.Knows,
|
|
218
|
+
* bidirectional: true // Creates both directions automatically
|
|
219
|
+
* })
|
|
220
|
+
*
|
|
221
|
+
* @example
|
|
222
|
+
* // Weighted relationships for importance/strength
|
|
223
|
+
* const collaborationId = await brainy.relate({
|
|
224
|
+
* from: 'team-lead',
|
|
225
|
+
* to: 'project-alpha',
|
|
226
|
+
* type: VerbType.LeadsOn,
|
|
227
|
+
* weight: 0.9, // High importance/strength
|
|
228
|
+
* metadata: {
|
|
229
|
+
* startDate: '2024-01-15',
|
|
230
|
+
* responsibility: 'technical leadership',
|
|
231
|
+
* hoursPerWeek: 40
|
|
232
|
+
* }
|
|
233
|
+
* })
|
|
234
|
+
*
|
|
235
|
+
* @example
|
|
236
|
+
* // Typed relationships with custom metadata
|
|
237
|
+
* interface CollaborationMeta {
|
|
238
|
+
* role: string
|
|
239
|
+
* startDate: string
|
|
240
|
+
* skillLevel: number
|
|
241
|
+
* }
|
|
242
|
+
*
|
|
243
|
+
* const brainy = new Brainy<CollaborationMeta>({ storage: 'filesystem' })
|
|
244
|
+
* const relationId = await brainy.relate({
|
|
245
|
+
* from: 'developer-123',
|
|
246
|
+
* to: 'project-456',
|
|
247
|
+
* type: VerbType.WorksOn,
|
|
248
|
+
* weight: 0.85,
|
|
249
|
+
* metadata: {
|
|
250
|
+
* role: 'frontend developer',
|
|
251
|
+
* startDate: '2024-03-01',
|
|
252
|
+
* skillLevel: 8
|
|
253
|
+
* }
|
|
254
|
+
* })
|
|
255
|
+
*
|
|
256
|
+
* @example
|
|
257
|
+
* // Creating complex relationship networks
|
|
258
|
+
* const entities = []
|
|
259
|
+
* // Create entities
|
|
260
|
+
* for (let i = 0; i < 5; i++) {
|
|
261
|
+
* const id = await brainy.add({
|
|
262
|
+
* data: { name: `Entity ${i}`, value: i * 10 },
|
|
263
|
+
* type: NounType.Thing
|
|
264
|
+
* })
|
|
265
|
+
* entities.push(id)
|
|
266
|
+
* }
|
|
267
|
+
*
|
|
268
|
+
* // Create hierarchical relationships
|
|
269
|
+
* for (let i = 0; i < entities.length - 1; i++) {
|
|
270
|
+
* await brainy.relate({
|
|
271
|
+
* from: entities[i],
|
|
272
|
+
* to: entities[i + 1],
|
|
273
|
+
* type: VerbType.DependsOn,
|
|
274
|
+
* weight: (i + 1) / entities.length
|
|
275
|
+
* })
|
|
276
|
+
* }
|
|
277
|
+
*
|
|
278
|
+
* @example
|
|
279
|
+
* // Error handling for invalid relationships
|
|
280
|
+
* try {
|
|
281
|
+
* await brainy.relate({
|
|
282
|
+
* from: 'nonexistent-entity',
|
|
283
|
+
* to: 'another-entity',
|
|
284
|
+
* type: VerbType.RelatedTo
|
|
285
|
+
* })
|
|
286
|
+
* } catch (error) {
|
|
287
|
+
* if (error.message.includes('not found')) {
|
|
288
|
+
* console.log('One or both entities do not exist')
|
|
289
|
+
* // Handle missing entities...
|
|
290
|
+
* }
|
|
291
|
+
* }
|
|
79
292
|
*/
|
|
80
293
|
relate(params: RelateParams<T>): Promise<string>;
|
|
81
294
|
/**
|
|
@@ -89,10 +302,252 @@ export declare class Brainy<T = any> implements BrainyInterface<T> {
|
|
|
89
302
|
/**
|
|
90
303
|
* Unified find method - supports natural language and structured queries
|
|
91
304
|
* Implements Triple Intelligence with parallel search optimization
|
|
305
|
+
*
|
|
306
|
+
* @param query - Natural language string or structured FindParams object
|
|
307
|
+
* @returns Promise that resolves to array of search results with scores
|
|
308
|
+
*
|
|
309
|
+
* @example
|
|
310
|
+
* // Natural language queries (most common)
|
|
311
|
+
* const results = await brainy.find('users who work on AI projects')
|
|
312
|
+
* const docs = await brainy.find('documents about machine learning')
|
|
313
|
+
* const code = await brainy.find('JavaScript functions for data processing')
|
|
314
|
+
*
|
|
315
|
+
* @example
|
|
316
|
+
* // Structured queries with filtering
|
|
317
|
+
* const results = await brainy.find({
|
|
318
|
+
* query: 'artificial intelligence',
|
|
319
|
+
* type: NounType.Document,
|
|
320
|
+
* limit: 5,
|
|
321
|
+
* where: {
|
|
322
|
+
* status: 'published',
|
|
323
|
+
* author: 'expert'
|
|
324
|
+
* }
|
|
325
|
+
* })
|
|
326
|
+
*
|
|
327
|
+
* // Process results
|
|
328
|
+
* for (const result of results) {
|
|
329
|
+
* console.log(`Found: ${result.entity.data} (score: ${result.score})`)
|
|
330
|
+
* }
|
|
331
|
+
*
|
|
332
|
+
* @example
|
|
333
|
+
* // Metadata-only filtering (no vector search)
|
|
334
|
+
* const activeUsers = await brainy.find({
|
|
335
|
+
* type: NounType.Person,
|
|
336
|
+
* where: {
|
|
337
|
+
* status: 'active',
|
|
338
|
+
* department: 'engineering'
|
|
339
|
+
* },
|
|
340
|
+
* service: 'user-management'
|
|
341
|
+
* })
|
|
342
|
+
*
|
|
343
|
+
* @example
|
|
344
|
+
* // Vector similarity search with custom vectors
|
|
345
|
+
* const queryVector = await brainy.embed('machine learning algorithms')
|
|
346
|
+
* const similar = await brainy.find({
|
|
347
|
+
* vector: queryVector,
|
|
348
|
+
* limit: 10,
|
|
349
|
+
* type: [NounType.Document, NounType.Thing]
|
|
350
|
+
* })
|
|
351
|
+
*
|
|
352
|
+
* @example
|
|
353
|
+
* // Proximity search (find entities similar to existing ones)
|
|
354
|
+
* const relatedContent = await brainy.find({
|
|
355
|
+
* near: 'document-123', // Find entities similar to this one
|
|
356
|
+
* limit: 8,
|
|
357
|
+
* where: {
|
|
358
|
+
* published: true
|
|
359
|
+
* }
|
|
360
|
+
* })
|
|
361
|
+
*
|
|
362
|
+
* @example
|
|
363
|
+
* // Pagination for large result sets
|
|
364
|
+
* const firstPage = await brainy.find({
|
|
365
|
+
* query: 'research papers',
|
|
366
|
+
* limit: 20,
|
|
367
|
+
* offset: 0
|
|
368
|
+
* })
|
|
369
|
+
*
|
|
370
|
+
* const secondPage = await brainy.find({
|
|
371
|
+
* query: 'research papers',
|
|
372
|
+
* limit: 20,
|
|
373
|
+
* offset: 20
|
|
374
|
+
* })
|
|
375
|
+
*
|
|
376
|
+
* @example
|
|
377
|
+
* // Complex search with multiple criteria
|
|
378
|
+
* const results = await brainy.find({
|
|
379
|
+
* query: 'machine learning models',
|
|
380
|
+
* type: [NounType.Thing, NounType.Document],
|
|
381
|
+
* where: {
|
|
382
|
+
* accuracy: { $gte: 0.9 }, // Metadata filtering
|
|
383
|
+
* framework: { $in: ['tensorflow', 'pytorch'] }
|
|
384
|
+
* },
|
|
385
|
+
* service: 'ml-pipeline',
|
|
386
|
+
* limit: 15
|
|
387
|
+
* })
|
|
388
|
+
*
|
|
389
|
+
* @example
|
|
390
|
+
* // Empty query returns all entities (paginated)
|
|
391
|
+
* const allEntities = await brainy.find({
|
|
392
|
+
* limit: 50,
|
|
393
|
+
* offset: 0
|
|
394
|
+
* })
|
|
395
|
+
*
|
|
396
|
+
* @example
|
|
397
|
+
* // Performance-optimized search patterns
|
|
398
|
+
* // Fast metadata-only search (no vector computation)
|
|
399
|
+
* const fastResults = await brainy.find({
|
|
400
|
+
* type: NounType.Person,
|
|
401
|
+
* where: { active: true },
|
|
402
|
+
* limit: 100
|
|
403
|
+
* })
|
|
404
|
+
*
|
|
405
|
+
* // Combined vector + metadata for precision
|
|
406
|
+
* const preciseResults = await brainy.find({
|
|
407
|
+
* query: 'senior developers',
|
|
408
|
+
* where: {
|
|
409
|
+
* experience: { $gte: 5 },
|
|
410
|
+
* skills: { $includes: 'javascript' }
|
|
411
|
+
* },
|
|
412
|
+
* limit: 10
|
|
413
|
+
* })
|
|
414
|
+
*
|
|
415
|
+
* @example
|
|
416
|
+
* // Error handling and result processing
|
|
417
|
+
* try {
|
|
418
|
+
* const results = await brainy.find('complex query here')
|
|
419
|
+
*
|
|
420
|
+
* if (results.length === 0) {
|
|
421
|
+
* console.log('No results found')
|
|
422
|
+
* return
|
|
423
|
+
* }
|
|
424
|
+
*
|
|
425
|
+
* // Filter by confidence threshold
|
|
426
|
+
* const highConfidence = results.filter(r => r.score > 0.7)
|
|
427
|
+
*
|
|
428
|
+
* // Sort by score (already sorted by default)
|
|
429
|
+
* const topResults = results.slice(0, 5)
|
|
430
|
+
*
|
|
431
|
+
* return topResults.map(r => ({
|
|
432
|
+
* id: r.id,
|
|
433
|
+
* content: r.entity.data,
|
|
434
|
+
* confidence: r.score,
|
|
435
|
+
* metadata: r.entity.metadata
|
|
436
|
+
* }))
|
|
437
|
+
* } catch (error) {
|
|
438
|
+
* console.error('Search failed:', error)
|
|
439
|
+
* return []
|
|
440
|
+
* }
|
|
92
441
|
*/
|
|
93
442
|
find(query: string | FindParams<T>): Promise<Result<T>[]>;
|
|
94
443
|
/**
|
|
95
|
-
* Find similar entities
|
|
444
|
+
* Find similar entities using vector similarity
|
|
445
|
+
*
|
|
446
|
+
* @param params - Parameters specifying the target for similarity search
|
|
447
|
+
* @returns Promise that resolves to array of similar entities with similarity scores
|
|
448
|
+
*
|
|
449
|
+
* @example
|
|
450
|
+
* // Find entities similar to a specific entity by ID
|
|
451
|
+
* const similarDocs = await brainy.similar({
|
|
452
|
+
* to: 'document-123',
|
|
453
|
+
* limit: 10
|
|
454
|
+
* })
|
|
455
|
+
*
|
|
456
|
+
* // Process similarity results
|
|
457
|
+
* for (const result of similarDocs) {
|
|
458
|
+
* console.log(`Similar entity: ${result.entity.data} (similarity: ${result.score})`)
|
|
459
|
+
* }
|
|
460
|
+
*
|
|
461
|
+
* @example
|
|
462
|
+
* // Find similar entities with type filtering
|
|
463
|
+
* const similarUsers = await brainy.similar({
|
|
464
|
+
* to: 'user-456',
|
|
465
|
+
* type: NounType.Person,
|
|
466
|
+
* limit: 5,
|
|
467
|
+
* where: {
|
|
468
|
+
* active: true,
|
|
469
|
+
* department: 'engineering'
|
|
470
|
+
* }
|
|
471
|
+
* })
|
|
472
|
+
*
|
|
473
|
+
* @example
|
|
474
|
+
* // Find similar using a custom vector
|
|
475
|
+
* const customVector = await brainy.embed('artificial intelligence research')
|
|
476
|
+
* const similar = await brainy.similar({
|
|
477
|
+
* to: customVector,
|
|
478
|
+
* limit: 8,
|
|
479
|
+
* type: [NounType.Document, NounType.Thing]
|
|
480
|
+
* })
|
|
481
|
+
*
|
|
482
|
+
* @example
|
|
483
|
+
* // Find similar using an entity object
|
|
484
|
+
* const sourceEntity = await brainy.get('research-paper-789')
|
|
485
|
+
* if (sourceEntity) {
|
|
486
|
+
* const relatedPapers = await brainy.similar({
|
|
487
|
+
* to: sourceEntity,
|
|
488
|
+
* limit: 12,
|
|
489
|
+
* where: {
|
|
490
|
+
* published: true,
|
|
491
|
+
* category: 'machine-learning'
|
|
492
|
+
* }
|
|
493
|
+
* })
|
|
494
|
+
* }
|
|
495
|
+
*
|
|
496
|
+
* @example
|
|
497
|
+
* // Content recommendation system
|
|
498
|
+
* async function getRecommendations(userId: string) {
|
|
499
|
+
* // Get user's recent interactions
|
|
500
|
+
* const user = await brainy.get(userId)
|
|
501
|
+
* if (!user) return []
|
|
502
|
+
*
|
|
503
|
+
* // Find similar content
|
|
504
|
+
* const recommendations = await brainy.similar({
|
|
505
|
+
* to: userId,
|
|
506
|
+
* type: NounType.Document,
|
|
507
|
+
* limit: 20,
|
|
508
|
+
* where: {
|
|
509
|
+
* published: true,
|
|
510
|
+
* language: 'en'
|
|
511
|
+
* }
|
|
512
|
+
* })
|
|
513
|
+
*
|
|
514
|
+
* // Filter out already seen content
|
|
515
|
+
* return recommendations.filter(rec =>
|
|
516
|
+
* !user.metadata.viewedItems?.includes(rec.id)
|
|
517
|
+
* )
|
|
518
|
+
* }
|
|
519
|
+
*
|
|
520
|
+
* @example
|
|
521
|
+
* // Duplicate detection system
|
|
522
|
+
* async function findPotentialDuplicates(entityId: string) {
|
|
523
|
+
* const duplicates = await brainy.similar({
|
|
524
|
+
* to: entityId,
|
|
525
|
+
* limit: 10
|
|
526
|
+
* })
|
|
527
|
+
*
|
|
528
|
+
* // High similarity might indicate duplicates
|
|
529
|
+
* const highSimilarity = duplicates.filter(d => d.score > 0.95)
|
|
530
|
+
*
|
|
531
|
+
* if (highSimilarity.length > 0) {
|
|
532
|
+
* console.log('Potential duplicates found:', highSimilarity.map(d => d.id))
|
|
533
|
+
* }
|
|
534
|
+
*
|
|
535
|
+
* return highSimilarity
|
|
536
|
+
* }
|
|
537
|
+
*
|
|
538
|
+
* @example
|
|
539
|
+
* // Error handling for missing entities
|
|
540
|
+
* try {
|
|
541
|
+
* const similar = await brainy.similar({
|
|
542
|
+
* to: 'nonexistent-entity',
|
|
543
|
+
* limit: 5
|
|
544
|
+
* })
|
|
545
|
+
* } catch (error) {
|
|
546
|
+
* if (error.message.includes('not found')) {
|
|
547
|
+
* console.log('Source entity does not exist')
|
|
548
|
+
* // Handle missing source entity
|
|
549
|
+
* }
|
|
550
|
+
* }
|
|
96
551
|
*/
|
|
97
552
|
similar(params: SimilarParams<T>): Promise<Result<T>[]>;
|
|
98
553
|
/**
|
|
@@ -342,8 +797,117 @@ export declare class Brainy<T = any> implements BrainyInterface<T> {
|
|
|
342
797
|
*/
|
|
343
798
|
private verbsToRelations;
|
|
344
799
|
/**
|
|
345
|
-
* Embed data into vector
|
|
346
|
-
* Handles any data type by converting to string representation
|
|
800
|
+
* Embed data into vector representation
|
|
801
|
+
* Handles any data type by intelligently converting to string representation
|
|
802
|
+
*
|
|
803
|
+
* @param data - Any data to convert to vector (string, object, array, etc.)
|
|
804
|
+
* @returns Promise that resolves to a numerical vector representation
|
|
805
|
+
*
|
|
806
|
+
* @example
|
|
807
|
+
* // Basic string embedding
|
|
808
|
+
* const vector = await brainy.embed('machine learning algorithms')
|
|
809
|
+
* console.log('Vector dimensions:', vector.length)
|
|
810
|
+
*
|
|
811
|
+
* @example
|
|
812
|
+
* // Object embedding with intelligent field extraction
|
|
813
|
+
* const documentVector = await brainy.embed({
|
|
814
|
+
* title: 'AI Research Paper',
|
|
815
|
+
* content: 'This paper discusses neural networks...',
|
|
816
|
+
* author: 'Dr. Smith',
|
|
817
|
+
* category: 'machine-learning'
|
|
818
|
+
* })
|
|
819
|
+
* // Uses 'content' field for embedding by default
|
|
820
|
+
*
|
|
821
|
+
* @example
|
|
822
|
+
* // Different object field priorities
|
|
823
|
+
* // Priority: data > content > text > name > title > description
|
|
824
|
+
* const vectors = await Promise.all([
|
|
825
|
+
* brainy.embed({ data: 'primary content' }), // Uses 'data'
|
|
826
|
+
* brainy.embed({ content: 'main content' }), // Uses 'content'
|
|
827
|
+
* brainy.embed({ text: 'text content' }), // Uses 'text'
|
|
828
|
+
* brainy.embed({ name: 'entity name' }), // Uses 'name'
|
|
829
|
+
* brainy.embed({ title: 'document title' }), // Uses 'title'
|
|
830
|
+
* brainy.embed({ description: 'description text' }) // Uses 'description'
|
|
831
|
+
* ])
|
|
832
|
+
*
|
|
833
|
+
* @example
|
|
834
|
+
* // Array embedding for batch processing
|
|
835
|
+
* const batchVectors = await brainy.embed([
|
|
836
|
+
* 'first document',
|
|
837
|
+
* 'second document',
|
|
838
|
+
* { content: 'third document as object' },
|
|
839
|
+
* { title: 'fourth document' }
|
|
840
|
+
* ])
|
|
841
|
+
* // Returns vector representing all items combined
|
|
842
|
+
*
|
|
843
|
+
* @example
|
|
844
|
+
* // Complex object handling
|
|
845
|
+
* const complexData = {
|
|
846
|
+
* user: { name: 'John', role: 'developer' },
|
|
847
|
+
* project: { name: 'AI Assistant', status: 'active' },
|
|
848
|
+
* metrics: { score: 0.95, performance: 'excellent' }
|
|
849
|
+
* }
|
|
850
|
+
* const vector = await brainy.embed(complexData)
|
|
851
|
+
* // Converts entire object to JSON for embedding
|
|
852
|
+
*
|
|
853
|
+
* @example
|
|
854
|
+
* // Pre-computing vectors for performance optimization
|
|
855
|
+
* const documents = [
|
|
856
|
+
* { id: 'doc1', content: 'Document 1 content...' },
|
|
857
|
+
* { id: 'doc2', content: 'Document 2 content...' },
|
|
858
|
+
* { id: 'doc3', content: 'Document 3 content...' }
|
|
859
|
+
* ]
|
|
860
|
+
*
|
|
861
|
+
* // Pre-compute all vectors
|
|
862
|
+
* const vectors = await Promise.all(
|
|
863
|
+
* documents.map(doc => brainy.embed(doc.content))
|
|
864
|
+
* )
|
|
865
|
+
*
|
|
866
|
+
* // Add entities with pre-computed vectors (faster)
|
|
867
|
+
* for (let i = 0; i < documents.length; i++) {
|
|
868
|
+
* await brainy.add({
|
|
869
|
+
* data: documents[i],
|
|
870
|
+
* type: NounType.Document,
|
|
871
|
+
* vector: vectors[i] // Skip embedding computation
|
|
872
|
+
* })
|
|
873
|
+
* }
|
|
874
|
+
*
|
|
875
|
+
* @example
|
|
876
|
+
* // Custom embedding for search queries
|
|
877
|
+
* async function searchWithCustomEmbedding(query: string) {
|
|
878
|
+
* // Enhance query for better matching
|
|
879
|
+
* const enhancedQuery = `search: ${query} relevant information`
|
|
880
|
+
* const queryVector = await brainy.embed(enhancedQuery)
|
|
881
|
+
*
|
|
882
|
+
* // Use pre-computed vector for search
|
|
883
|
+
* return brainy.find({
|
|
884
|
+
* vector: queryVector,
|
|
885
|
+
* limit: 10
|
|
886
|
+
* })
|
|
887
|
+
* }
|
|
888
|
+
*
|
|
889
|
+
* @example
|
|
890
|
+
* // Handling edge cases gracefully
|
|
891
|
+
* const edgeCases = await Promise.all([
|
|
892
|
+
* brainy.embed(null), // Returns vector for empty string
|
|
893
|
+
* brainy.embed(undefined), // Returns vector for empty string
|
|
894
|
+
* brainy.embed(''), // Returns vector for empty string
|
|
895
|
+
* brainy.embed(42), // Converts number to string
|
|
896
|
+
* brainy.embed(true), // Converts boolean to string
|
|
897
|
+
* brainy.embed([]), // Empty array handling
|
|
898
|
+
* brainy.embed({}) // Empty object handling
|
|
899
|
+
* ])
|
|
900
|
+
*
|
|
901
|
+
* @example
|
|
902
|
+
* // Using with similarity comparisons
|
|
903
|
+
* const doc1Vector = await brainy.embed('artificial intelligence research')
|
|
904
|
+
* const doc2Vector = await brainy.embed('machine learning algorithms')
|
|
905
|
+
*
|
|
906
|
+
* // Find entities similar to doc1Vector
|
|
907
|
+
* const similar = await brainy.find({
|
|
908
|
+
* vector: doc1Vector,
|
|
909
|
+
* limit: 5
|
|
910
|
+
* })
|
|
347
911
|
*/
|
|
348
912
|
embed(data: any): Promise<Vector>;
|
|
349
913
|
/**
|