docs: add deprecation warnings for addNoun and addVerb methods

- Add @deprecated JSDoc tags to TypeScript definitions
- Update all documentation examples to use modern add() and relate() API
- Preserve batch operations (addNouns, addVerbs) as they remain current
- Mark deprecated methods in both source and compiled definitions

Migration guide:
- addNoun(data, type, metadata) → add(data, { nounType: type, ...metadata })
- addVerb(source, target, type, metadata) → relate(source, target, type, metadata)
This commit is contained in:
David Snelling 2025-09-17 10:48:41 -07:00
parent 6e299c576c
commit e311a149df
21 changed files with 343 additions and 331 deletions

View file

@ -315,10 +315,10 @@ const results = await brain.find({
```javascript ```javascript
// Create entities (nouns) // Create entities (nouns)
const id = await brain.addNoun(data, nounType, metadata) const id = await brain.add(data, { nounType: nounType, ...metadata })
// Create relationships (verbs) // Create relationships (verbs)
const verbId = await brain.addVerb(sourceId, targetId, "relationType", { const verbId = await brain.relate(sourceId, targetId, "relationType", {
strength: 0.9, strength: 0.9,
bidirectional: false bidirectional: false
}) })
@ -377,7 +377,8 @@ const ingestionNode = new Brainy({
// Process Bluesky firehose // Process Bluesky firehose
blueskyStream.on('post', async (post) => { blueskyStream.on('post', async (post) => {
await ingestionNode.addNoun(post, 'social-post', { await ingestionNode.add(post, {
nounType: 'social-post',
platform: 'bluesky', platform: 'bluesky',
author: post.author, author: post.author,
timestamp: post.createdAt timestamp: post.createdAt
@ -415,27 +416,30 @@ const trending = await searchNode.find('trending AI topics', {
```javascript ```javascript
// Store documentation with rich relationships // Store documentation with rich relationships
const apiGuide = await brain.addNoun("REST API Guide", 'document', { const apiGuide = await brain.add("REST API Guide", {
nounType: 'document',
title: "API Guide", title: "API Guide",
category: "documentation", category: "documentation",
version: "2.0" version: "2.0"
}) })
const author = await brain.addNoun("Jane Developer", 'person', { const author = await brain.add("Jane Developer", {
nounType: 'person',
type: "person", type: "person",
role: "tech-lead" role: "tech-lead"
}) })
const project = await brain.addNoun("E-commerce Platform", 'project', { const project = await brain.add("E-commerce Platform", {
nounType: 'project',
type: "project", type: "project",
status: "active" status: "active"
}) })
// Create knowledge graph // Create knowledge graph
await brain.addVerb(author, apiGuide, "authored", { await brain.relate(author, apiGuide, "authored", {
date: "2024-03-15" date: "2024-03-15"
}) })
await brain.addVerb(apiGuide, project, "documents", { await brain.relate(apiGuide, project, "documents", {
coverage: "complete" coverage: "complete"
}) })
@ -457,25 +461,28 @@ const similar = await brain.search(existingContent, {
```javascript ```javascript
// Store conversation with relationships // Store conversation with relationships
const userId = await brain.addNoun("User 123", 'user', { const userId = await brain.add("User 123", {
nounType: 'user',
type: "user", type: "user",
tier: "premium" tier: "premium"
}) })
const messageId = await brain.addNoun(userMessage, 'message', { const messageId = await brain.add(userMessage, {
nounType: 'message',
type: "message", type: "message",
timestamp: Date.now(), timestamp: Date.now(),
session: "abc" session: "abc"
}) })
const topicId = await brain.addNoun("Product Support", 'topic', { const topicId = await brain.add("Product Support", {
nounType: 'topic',
type: "topic", type: "topic",
category: "support" category: "support"
}) })
// Link conversation elements // Link conversation elements
await brain.addVerb(userId, messageId, "sent") await brain.relate(userId, messageId, "sent")
await brain.addVerb(messageId, topicId, "about") await brain.relate(messageId, topicId, "about")
// Retrieve context with relationships // Retrieve context with relationships
const context = await brain.find({ const context = await brain.find({
@ -595,7 +602,7 @@ for (const cluster of feedbackClusters) {
} }
// Find related documents // Find related documents
const docId = await brain.addNoun("Machine learning guide", 'document') const docId = await brain.add("Machine learning guide", { nounType: 'document' })
const similar = await neural.neighbors(docId, 5) const similar = await neural.neighbors(docId, 5)
// Returns 5 most similar documents // Returns 5 most similar documents

View file

@ -1227,9 +1227,9 @@ try {
### Old (v2.15) ### Old (v2.15)
```typescript ```typescript
brain.addNoun(data, 'document', metadata) brain.add({ data, type: NounType.Document, metadata })
brain.search(query, 10) brain.find({ query, limit: 10 })
brain.getStatistics() brain.insights()
``` ```
### New (v3.0) ### New (v3.0)

View file

@ -164,7 +164,7 @@ async execute(op, params, next) {
Common operations in Brainy: Common operations in Brainy:
- `'storage'` - Storage resolution (special) - `'storage'` - Storage resolution (special)
- `'add'`, `'addNoun'` - Adding data - `'add'` - Adding data
- `'search'`, `'similar'` - Searching - `'search'`, `'similar'` - Searching
- `'update'`, `'delete'` - Modifications - `'update'`, `'delete'` - Modifications
- `'saveNoun'`, `'saveVerb'` - Storage operations - `'saveNoun'`, `'saveVerb'` - Storage operations

View file

@ -34,21 +34,23 @@ That's it! No configuration needed. Brainy automatically:
```javascript ```javascript
// Add a simple string // Add a simple string
await brain.addNoun("JavaScript is a versatile programming language", 'concept') await brain.add("JavaScript is a versatile programming language", { nounType: 'concept' })
// Add with metadata // Add with metadata
await brain.addNoun("React is a JavaScript library", 'concept', { await brain.add("React is a JavaScript library", {
nounType: 'concept',
type: "library", type: "library",
category: "frontend", category: "frontend",
popularity: "high" popularity: "high"
}) })
// Add structured data // Add structured data
await brain.addNoun({ await brain.add({
title: "Introduction to TypeScript", title: "Introduction to TypeScript",
content: "TypeScript adds static typing to JavaScript", content: "TypeScript adds static typing to JavaScript",
author: "John Doe" author: "John Doe"
}, 'document', { }, {
nounType: 'document',
type: "article", type: "article",
date: "2024-01-15" date: "2024-01-15"
}) })
@ -94,7 +96,7 @@ const documents = [
] ]
for (const doc of documents) { for (const doc of documents) {
await brain.addNoun(doc.content, { await brain.add(doc.content, {
filename: doc.file, filename: doc.file,
type: 'documentation', type: 'documentation',
indexed: new Date().toISOString() indexed: new Date().toISOString()
@ -122,7 +124,7 @@ class ChatWithMemory {
} }
async addMessage(role, content) { async addMessage(role, content) {
await this.brain.addNoun(content, { await this.brain.add(content, {
role, role,
sessionId: this.sessionId, sessionId: this.sessionId,
timestamp: Date.now() timestamp: Date.now()
@ -177,7 +179,7 @@ for (const file of files) {
// Extract functions // Extract functions
const functions = content.match(/function\s+(\w+)|const\s+(\w+)\s*=/g) || [] const functions = content.match(/function\s+(\w+)|const\s+(\w+)\s*=/g) || []
await brain.addNoun(content, { await brain.add(content, {
file, file,
type: 'code', type: 'code',
language: 'javascript', language: 'javascript',

View file

@ -69,19 +69,19 @@ const brain = new BrainyData()
await brain.init() await brain.init()
// Add entities (nouns) // Add entities (nouns)
const articleId = await brain.addNoun("Revolutionary AI Breakthrough", { const articleId = await brain.add("Revolutionary AI Breakthrough", {
type: "article", type: "article",
category: "technology", category: "technology",
rating: 4.8 rating: 4.8
}) })
const authorId = await brain.addNoun("Dr. Sarah Chen", { const authorId = await brain.add("Dr. Sarah Chen", {
type: "person", type: "person",
role: "researcher" role: "researcher"
}) })
// Create relationships (verbs) // Create relationships (verbs)
await brain.addVerb(authorId, articleId, "authored", { await brain.relate(authorId, articleId, "authored", {
date: "2024-01-15", date: "2024-01-15",
contribution: "primary" contribution: "primary"
}) })

View file

@ -19,13 +19,13 @@ const brain = new BrainyData({ storage: { path: './my-data' } })
#### **2. Data Operations (CRUD)** #### **2. Data Operations (CRUD)**
```typescript ```typescript
// ✅ CONSISTENT: Always (data, type, metadata) pattern // ✅ CONSISTENT: Always (data, metadata) pattern with nounType in metadata
await brain.addNoun(content, NounType.Person, { role: 'Engineer' }) await brain.add(content, { nounType: NounType.Person, role: 'Engineer' })
await brain.addNoun(content, NounType.Document, { title: 'API Guide' }) await brain.add(content, { nounType: NounType.Document, title: 'API Guide' })
// ✅ CONSISTENT: Always (source, target, type, metadata) pattern // ✅ CONSISTENT: Always (source, target, type, metadata) pattern
await brain.addVerb(sourceId, targetId, VerbType.RelatedTo, { strength: 0.8 }) await brain.relate(sourceId, targetId, VerbType.RelatedTo, { strength: 0.8 })
await brain.addVerb(sourceId, targetId, VerbType.Contains, { confidence: 0.9 }) await brain.relate(sourceId, targetId, VerbType.Contains, { confidence: 0.9 })
// ✅ CONSISTENT: Batch versions take arrays // ✅ CONSISTENT: Batch versions take arrays
await brain.addNouns([...]) // Array of noun objects await brain.addNouns([...]) // Array of noun objects
@ -58,10 +58,10 @@ await brain.related(id, limit?) // Returns simple array
#### **Main Data Operations** (Direct on `brain`) #### **Main Data Operations** (Direct on `brain`)
```typescript ```typescript
// Core CRUD - most common operations // Core CRUD - most common operations
brain.addNoun(content, type, metadata?) brain.add(content, metadata)
brain.addNouns(items[]) brain.addNouns(items[]) // Batch operation - unchanged
brain.addVerb(source, target, type, metadata?) brain.relate(source, target, type, metadata?)
brain.addVerbs(items[]) brain.addVerbs(items[]) // Batch operation - unchanged
brain.search(query, options?) brain.search(query, options?)
brain.find(naturalLanguageQuery, options?) // Triple Intelligence brain.find(naturalLanguageQuery, options?) // Triple Intelligence
@ -138,7 +138,7 @@ brain.storage.vacuum()
const brain = new BrainyData() const brain = new BrainyData()
await brain.init() await brain.init()
await brain.addNoun('My first document', NounType.Document) await brain.add('My first document', { nounType: NounType.Document })
const results = await brain.search('document') const results = await brain.search('document')
const similar = await brain.similar('text1', 'text2') const similar = await brain.similar('text1', 'text2')
const groups = await brain.clusters() const groups = await brain.clusters()
@ -193,9 +193,9 @@ for await (const batch of brain.neural.clusterStream({ batchSize: 50 })) {
#### **1. Data-First Pattern** #### **1. Data-First Pattern**
```typescript ```typescript
// Always: (data, type/config, optional_metadata) // Always: (data, config/metadata, optional_params)
brain.addNoun(content, NounType.Document, metadata?) brain.add(content, metadata) // nounType now in metadata
brain.addVerb(source, target, VerbType.RelatedTo, metadata?) brain.relate(source, target, VerbType.RelatedTo, metadata?)
brain.search(query, options?) brain.search(query, options?)
brain.similar(a, b, options?) brain.similar(a, b, options?)
``` ```
@ -270,8 +270,8 @@ try {
import { BrainyData, NounType, VerbType } from '@soulcraft/brainy' import { BrainyData, NounType, VerbType } from '@soulcraft/brainy'
const brain = new BrainyData() const brain = new BrainyData()
await brain.addNoun('content', NounType.Document, { title: 'My Doc' }) await brain.add('content', { nounType: NounType.Document, title: 'My Doc' })
// ^^^^^^^^^^^^^^^^ // IDE autocomplete! // ^^^^^^^^^^^^^^^^ // IDE autocomplete!
``` ```
### **✅ 5. Flexible Configuration** ### **✅ 5. Flexible Configuration**
@ -306,7 +306,7 @@ const brain = new BrainyData({
* @param type - Relationship type (VerbType enum) * @param type - Relationship type (VerbType enum)
* @param metadata - Optional relationship metadata * @param metadata - Optional relationship metadata
*/ */
brain.addVerb(source, target, type, metadata?) brain.relate(source, target, type, metadata?)
``` ```
### **2. Error Context Enhancement** ### **2. Error Context Enhancement**

View file

@ -12,7 +12,7 @@ const brain = new BrainyData() // Zero config!
await brain.init() await brain.init()
// Add data (text auto-embeds!) // Add data (text auto-embeds!)
await brain.addNoun('The future of AI is here', 'content') await brain.add('The future of AI is here', { nounType: 'content' })
// Search with Triple Intelligence // Search with Triple Intelligence
const results = await brain.find({ const results = await brain.find({
@ -295,7 +295,7 @@ Brainy uses its own clean, readable operators:
### Basic Usage ### Basic Usage
```typescript ```typescript
// Add data // Add data
const id = await brain.addNoun('Quantum computing breakthrough', { const id = await brain.add('Quantum computing breakthrough', {
category: 'technology', category: 'technology',
year: 2024, year: 2024,
importance: 'high' importance: 'high'
@ -322,14 +322,14 @@ const articles = await brain.find({
### Creating Knowledge Graphs ### Creating Knowledge Graphs
```typescript ```typescript
// Add entities // Add entities
const ai = await brain.addNoun('Artificial Intelligence', 'concept') const ai = await brain.add('Artificial Intelligence', { nounType: 'concept' })
const ml = await brain.addNoun('Machine Learning', 'concept') const ml = await brain.add('Machine Learning', { nounType: 'concept' })
const dl = await brain.addNoun('Deep Learning', 'concept') const dl = await brain.add('Deep Learning', { nounType: 'concept' })
// Create relationships // Create relationships
await brain.addVerb(ml, ai, 'subset_of') await brain.relate(ml, ai, 'subset_of')
await brain.addVerb(dl, ml, 'subset_of') await brain.relate(dl, ml, 'subset_of')
await brain.addVerb(dl, ai, 'enables') await brain.relate(dl, ai, 'enables')
// Traverse the graph // Traverse the graph
const aiEcosystem = await brain.find({ const aiEcosystem = await brain.find({

View file

@ -47,7 +47,7 @@ VerbType: RelatedTo, Contains, PartOf, Causes, CreatedBy, etc.
#### **4. Graph Structure** #### **4. Graph Structure**
```typescript ```typescript
// VERB RELATIONSHIPS CREATE RICH GRAPH // VERB RELATIONSHIPS CREATE RICH GRAPH
await brain.addVerb(sourceId, targetId, VerbType.Causes, { strength: 0.8 }) await brain.relate(sourceId, targetId, VerbType.Causes, { strength: 0.8 })
``` ```
**Graph-based clustering potential:** **Graph-based clustering potential:**

View file

@ -26,8 +26,8 @@ const brain = new BrainyData({
}) })
// Automatically prevents duplicate entities // Automatically prevents duplicate entities
await brain.addNoun("Same content", { id: "123" }) // Added await brain.add("Same content", { id: "123" }) // Added
await brain.addNoun("Same content", { id: "123" }) // Skipped (duplicate) await brain.add("Same content", { id: "123" }) // Skipped (duplicate)
``` ```
**Benefits:** **Benefits:**
@ -85,8 +85,8 @@ const brain = new BrainyData({
}) })
// Relationships automatically get intelligent scores // Relationships automatically get intelligent scores
await brain.addVerb(user1, product1, "viewed", { timestamp: Date.now() }) await brain.relate(user1, product1, "viewed", { timestamp: Date.now() })
await brain.addVerb(user1, product1, "purchased", { timestamp: Date.now() }) await brain.relate(user1, product1, "purchased", { timestamp: Date.now() })
// Automatically calculates relationship strength based on multiple factors // Automatically calculates relationship strength based on multiple factors
// Query using intelligent scores // Query using intelligent scores
@ -122,7 +122,7 @@ const brain = new BrainyData({
}) })
// Automatically extracts and registers entities // Automatically extracts and registers entities
await brain.addNoun( await brain.add(
"Apple CEO Tim Cook announced the new iPhone 15 in Cupertino", "Apple CEO Tim Cook announced the new iPhone 15 in Cupertino",
{ type: "news" } { type: "news" }
) )
@ -160,7 +160,7 @@ const brain = new BrainyData({
// Operations are automatically batched // Operations are automatically batched
for (let i = 0; i < 10000; i++) { for (let i = 0; i < 10000; i++) {
await brain.addNoun(`Item ${i}`) // Internally batched await brain.add(`Item ${i}`) // Internally batched
} }
// Processes in optimized batches of 100 // Processes in optimized batches of 100
``` ```
@ -223,7 +223,7 @@ const brain = new BrainyData({
}) })
// Data automatically compressed/decompressed // Data automatically compressed/decompressed
await brain.addNoun(largeDocument) // Compressed before storage await brain.add(largeDocument) // Compressed before storage
const doc = await brain.getNoun(id) // Decompressed on retrieval const doc = await brain.getNoun(id) // Decompressed on retrieval
``` ```

File diff suppressed because it is too large Load diff

View file

@ -208,7 +208,7 @@ class DynamicBatcher {
// Automatically applied during bulk operations // Automatically applied during bulk operations
for (const item of millionItems) { for (const item of millionItems) {
await brain.addNoun(item) // Internally batched optimally await brain.add(item) // Internally batched optimally
} }
``` ```

View file

@ -184,7 +184,7 @@ const brain = new BrainyData({ wal: true })
**Purpose**: High-speed deduplication for real-time data **Purpose**: High-speed deduplication for real-time data
```typescript ```typescript
// Prevents duplicate entities in streaming scenarios // Prevents duplicate entities in streaming scenarios
brain.addNoun(data) // Automatically deduplicated brain.add(data) // Automatically deduplicated
``` ```
### AutoRegisterEntitiesAugmentation ### AutoRegisterEntitiesAugmentation

View file

@ -10,7 +10,7 @@ import { BaseAugmentation, BrainyAugmentation, AugmentationContext } from '@soul
export class MyFirstAugmentation extends BaseAugmentation { export class MyFirstAugmentation extends BaseAugmentation {
readonly name = 'my-first-augmentation' readonly name = 'my-first-augmentation'
readonly timing = 'after' as const // When to run: before | after | both readonly timing = 'after' as const // When to run: before | after | both
readonly operations = ['addNoun'] as const // Which operations to hook readonly operations = ['add'] as const // Which operations to hook
readonly priority = 10 // Execution order (lower = first) readonly priority = 10 // Execution order (lower = first)
protected async onInit(): Promise<void> { protected async onInit(): Promise<void> {
@ -24,7 +24,7 @@ export class MyFirstAugmentation extends BaseAugmentation {
context?: AugmentationContext context?: AugmentationContext
): Promise<T | void> { ): Promise<T | void> {
// Your augmentation logic // Your augmentation logic
if (operation === 'addNoun') { if (operation === 'add') {
console.log('Noun added:', params.noun) console.log('Noun added:', params.noun)
// You can access the brain instance // You can access the brain instance
const stats = await context?.brain.getStatistics() const stats = await context?.brain.getStatistics()
@ -53,7 +53,7 @@ brain.augmentations.register(new MyFirstAugmentation())
await brain.init() await brain.init()
// Now your augmentation runs automatically! // Now your augmentation runs automatically!
await brain.addNoun('Hello World') await brain.add('Hello World')
// Console: "Noun added: { id: '...', vector: [...], metadata: {} }" // Console: "Noun added: { id: '...', vector: [...], metadata: {} }"
``` ```
@ -75,7 +75,7 @@ await brain.init() // Calls aug.initialize() internally
### 3. Execution Phase ### 3. Execution Phase
```typescript ```typescript
await brain.addNoun('data') // Your execute() method runs await brain.add('data') // Your execute() method runs
``` ```
### 4. Shutdown Phase ### 4. Shutdown Phase
@ -93,7 +93,7 @@ class ValidationAugmentation extends BaseAugmentation {
readonly timing = 'before' as const readonly timing = 'before' as const
async execute<T>(operation: string, params: any): Promise<any> { async execute<T>(operation: string, params: any): Promise<any> {
if (operation === 'addNoun') { if (operation === 'add') {
// Validate and/or modify params // Validate and/or modify params
if (!params.content) { if (!params.content) {
throw new Error('Content required') throw new Error('Content required')
@ -146,14 +146,14 @@ class TimingAugmentation extends BaseAugmentation {
### Core Operations You Can Hook ### Core Operations You Can Hook
```typescript ```typescript
readonly operations = [ readonly operations = [
'addNoun', // Adding data 'add', // Adding data
'updateNoun', // Updating data 'update', // Updating data
'deleteNoun', // Deleting data 'delete', // Deleting data
'getNoun', // Retrieving data 'get', // Retrieving data
'search', // Searching 'search', // Searching
'find', // Triple Intelligence queries 'find', // Triple Intelligence queries
'addVerb', // Adding relationships 'relate', // Adding relationships
'deleteVerb', // Removing relationships 'unrelate', // Removing relationships
'clear', // Clearing data 'clear', // Clearing data
'all' // Hook ALL operations 'all' // Hook ALL operations
] as const ] as const
@ -162,7 +162,7 @@ readonly operations = [
### Example: Multi-Operation Hook ### Example: Multi-Operation Hook
```typescript ```typescript
class AuditAugmentation extends BaseAugmentation { class AuditAugmentation extends BaseAugmentation {
readonly operations = ['addNoun', 'updateNoun', 'deleteNoun'] as const readonly operations = ['add', 'update', 'delete'] as const
async execute<T>(operation: string, params: any): Promise<void> { async execute<T>(operation: string, params: any): Promise<void> {
// Log all data modifications // Log all data modifications
@ -209,7 +209,7 @@ class ContextAwareAugmentation extends BaseAugmentation {
class BackupAugmentation extends BaseAugmentation { class BackupAugmentation extends BaseAugmentation {
readonly name = 'backup' readonly name = 'backup'
readonly timing = 'after' as const readonly timing = 'after' as const
readonly operations = ['addNoun', 'updateNoun', 'deleteNoun'] as const readonly operations = ['add', 'update', 'delete'] as const
readonly priority = 5 readonly priority = 5
private changes = 0 private changes = 0
@ -272,11 +272,11 @@ class RateLimitAugmentation extends BaseAugmentation {
class EncryptionAugmentation extends BaseAugmentation { class EncryptionAugmentation extends BaseAugmentation {
readonly name = 'encryption' readonly name = 'encryption'
readonly timing = 'both' as const readonly timing = 'both' as const
readonly operations = ['addNoun', 'getNoun'] as const readonly operations = ['add', 'get'] as const
readonly priority = 90 // Run early readonly priority = 90 // Run early
async execute<T>(operation: string, params: any): Promise<any> { async execute<T>(operation: string, params: any): Promise<any> {
if (operation === 'addNoun') { if (operation === 'add') {
// Encrypt before storing // Encrypt before storing
if (params.metadata?.sensitive) { if (params.metadata?.sensitive) {
params.content = await this.encrypt(params.content) params.content = await this.encrypt(params.content)
@ -285,7 +285,7 @@ class EncryptionAugmentation extends BaseAugmentation {
return params return params
} }
if (operation === 'getNoun' && params.result?.encrypted) { if (operation === 'get' && params.result?.encrypted) {
// Decrypt after retrieval // Decrypt after retrieval
params.result.content = await this.decrypt(params.result.content) params.result.content = await this.decrypt(params.result.content)
delete params.result.encrypted delete params.result.encrypted
@ -316,11 +316,11 @@ describe('MyAugmentation', () => {
await brain.init() await brain.init()
// Trigger the augmentation // Trigger the augmentation
await brain.addNoun('test data') await brain.add('test data')
// Verify it was called // Verify it was called
expect(executeSpy).toHaveBeenCalledWith( expect(executeSpy).toHaveBeenCalledWith(
'addNoun', 'add',
expect.objectContaining({ content: 'test data' }), expect.objectContaining({ content: 'test data' }),
expect.any(Object) expect.any(Object)
) )
@ -431,7 +431,7 @@ my-augmentation/
"type": "augmentation", "type": "augmentation",
"class": "CustomAugmentation", "class": "CustomAugmentation",
"timing": "after", "timing": "after",
"operations": ["addNoun"], "operations": ["add"],
"priority": 10 "priority": 10
} }
} }

View file

@ -391,7 +391,7 @@ const brain = new BrainyData()
await brain.init() await brain.init()
// Add data (auto-detects type) // Add data (auto-detects type)
await brain.addNoun('Content here') await brain.add('Content here')
// Search with natural language // Search with natural language
const results = await brain.find('related content from last week') const results = await brain.find('related content from last week')

View file

@ -404,7 +404,7 @@ const brain = new BrainyData()
await brain.init() await brain.init()
// You're now running the same tech as Fortune 500 companies // You're now running the same tech as Fortune 500 companies
await brain.addNoun("Your data is enterprise-grade", { await brain.add("Your data is enterprise-grade", {
secure: true, secure: true,
durable: true, durable: true,
scalable: true, scalable: true,

View file

@ -56,7 +56,7 @@ await brain.init()
```typescript ```typescript
// Add entities (nouns) with automatic embedding generation // Add entities (nouns) with automatic embedding generation
const id = await brain.addNoun("The quick brown fox jumps over the lazy dog", { const id = await brain.add("The quick brown fox jumps over the lazy dog", {
category: "demo", category: "demo",
timestamp: Date.now() timestamp: Date.now()
}) })
@ -64,9 +64,9 @@ const id = await brain.addNoun("The quick brown fox jumps over the lazy dog", {
console.log(`Added noun with ID: ${id}`) console.log(`Added noun with ID: ${id}`)
// Add relationships (verbs) between entities // Add relationships (verbs) between entities
const sourceId = await brain.addNoun("John Smith", 'person') const sourceId = await brain.add("John Smith", { nounType: 'person' })
const targetId = await brain.addNoun("TechCorp", 'organization') const targetId = await brain.add("TechCorp", { nounType: 'organization' })
await brain.addVerb(sourceId, targetId, "works_at", { await brain.relate(sourceId, targetId, "works_at", {
position: "Engineer", position: "Engineer",
since: "2024" since: "2024"
}) })
@ -118,7 +118,7 @@ const documents = [
] ]
for (const doc of documents) { for (const doc of documents) {
await brain.addNoun(doc.content, { await brain.add(doc.content, {
title: doc.title, title: doc.title,
type: "document" type: "document"
}) })
@ -132,7 +132,7 @@ const results = await brain.search("how do neural networks work")
```typescript ```typescript
// Add user interactions as nouns // Add user interactions as nouns
const interactionId = await brain.addNoun("user viewed product", { const interactionId = await brain.add("user viewed product", {
userId: "user123", userId: "user123",
productId: "product456", productId: "product456",
action: "view", action: "view",
@ -140,9 +140,9 @@ const interactionId = await brain.addNoun("user viewed product", {
}) })
// Create relationships between users and products // Create relationships between users and products
const userId = await brain.addNoun("user123", 'user') const userId = await brain.add("user123", { nounType: 'user' })
const productId = await brain.addNoun("product456", 'product') const productId = await brain.add("product456", { nounType: 'product' })
await brain.addVerb(userId, productId, "viewed", { await brain.relate(userId, productId, "viewed", {
timestamp: Date.now() timestamp: Date.now()
}) })
@ -161,18 +161,18 @@ const similar = await brain.find({
```typescript ```typescript
// Add entities (nouns) to the knowledge graph // Add entities (nouns) to the knowledge graph
const personId = await brain.addNoun("John Smith, Software Engineer", { const personId = await brain.add("John Smith, Software Engineer", {
type: "person", type: "person",
role: "engineer" role: "engineer"
}) })
const companyId = await brain.addNoun("TechCorp, Innovation Leader", { const companyId = await brain.add("TechCorp, Innovation Leader", {
type: "company", type: "company",
industry: "technology" industry: "technology"
}) })
// Create relationship // Create relationship
await brain.addVerb(personId, companyId, "works_at", { await brain.relate(personId, companyId, "works_at", {
since: "2020", since: "2020",
position: "Senior Engineer" position: "Senior Engineer"
}) })
@ -203,7 +203,7 @@ const brain = new BrainyData({
// Process streaming data // Process streaming data
async function processStream(item) { async function processStream(item) {
// Entity registry prevents duplicate nouns // Entity registry prevents duplicate nouns
const id = await brain.addNoun(item.content, { const id = await brain.add(item.content, {
externalId: item.id, externalId: item.id,
timestamp: item.timestamp timestamp: item.timestamp
}) })
@ -264,7 +264,7 @@ const brain = new BrainyData({
// Good - batch operations for nouns // Good - batch operations for nouns
const items = ["item1", "item2", "item3"] const items = ["item1", "item2", "item3"]
for (const item of items) { for (const item of items) {
await brain.addNoun(item, { batch: true }) await brain.add(item, { batch: true })
} }
// Create relationships efficiently // Create relationships efficiently
@ -273,7 +273,7 @@ const relationships = [
{ source: id2, target: id3, type: "similar" } { source: id2, target: id3, type: "similar" }
] ]
for (const rel of relationships) { for (const rel of relationships) {
await brain.addVerb(rel.source, rel.target, rel.type) await brain.relate(rel.source, rel.target, rel.type)
} }
``` ```
@ -307,7 +307,7 @@ const brain = new BrainyData({
```typescript ```typescript
try { try {
await brain.addNoun("content", metadata) await brain.add("content", metadata)
} catch (error) { } catch (error) {
if (error.code === 'STORAGE_FULL') { if (error.code === 'STORAGE_FULL') {
console.error('Storage is full') console.error('Storage is full')

View file

@ -302,7 +302,7 @@ const response = await openai.embeddings.create({
// After: Local Brainy embeddings // After: Local Brainy embeddings
const brain = new BrainyData() const brain = new BrainyData()
await brain.init() // One-time setup await brain.init() // One-time setup
const id = await brain.addNoun("Your text", 'content') // Embedded automatically const id = await brain.add("Your text", { nounType: 'content' }) // Embedded automatically
``` ```
### From Sentence Transformers ### From Sentence Transformers

View file

@ -43,12 +43,12 @@ const clusters = await neural.clusters()
// Example: Organize customer feedback // Example: Organize customer feedback
const feedback = [ const feedback = [
await brain.addNoun("The app crashes when I upload photos"), await brain.add("The app crashes when I upload photos"),
await brain.addNoun("Photo upload feature is broken"), await brain.add("Photo upload feature is broken"),
await brain.addNoun("Great customer service!"), await brain.add("Great customer service!"),
await brain.addNoun("Support team was very helpful"), await brain.add("Support team was very helpful"),
await brain.addNoun("Pricing is too high"), await brain.add("Pricing is too high"),
await brain.addNoun("Too expensive for what it offers") await brain.add("Too expensive for what it offers")
] ]
const themes = await neural.clusters() const themes = await neural.clusters()
@ -119,7 +119,7 @@ const neighbors = await neural.neighbors('item-id', 5)
// - data: The actual content // - data: The actual content
// Example: Recommend similar articles // Example: Recommend similar articles
const articleId = await brain.addNoun("Guide to React Hooks") const articleId = await brain.add("Guide to React Hooks")
const similar = await neural.neighbors(articleId, 3) const similar = await neural.neighbors(articleId, 3)
for (const article of similar) { for (const article of similar) {
@ -166,10 +166,10 @@ const outliers = await neural.outliers(0.3)
// Example: Detect spam or unusual content // Example: Detect spam or unusual content
const messages = [ const messages = [
await brain.addNoun("Meeting at 3pm"), await brain.add("Meeting at 3pm"),
await brain.addNoun("Lunch plans for tomorrow"), await brain.add("Lunch plans for tomorrow"),
await brain.addNoun("BUY NOW!!! AMAZING DEALS!!!"), await brain.add("BUY NOW!!! AMAZING DEALS!!!"),
await brain.addNoun("Project deadline next week") await brain.add("Project deadline next week")
] ]
const suspicious = await neural.outliers(0.4) const suspicious = await neural.outliers(0.4)
@ -238,7 +238,7 @@ const sameTopicArticles = currentTopic.members
// Add feedback with metadata // Add feedback with metadata
const feedbackIds = [] const feedbackIds = []
for (const feedback of customerFeedback) { for (const feedback of customerFeedback) {
const id = await brain.addNoun(feedback.text, { const id = await brain.add(feedback.text, {
rating: feedback.rating, rating: feedback.rating,
date: feedback.date, date: feedback.date,
product: feedback.product product: feedback.product

View file

@ -159,7 +159,7 @@ const brain = new BrainyData({
2. **Verify embedding generation** 2. **Verify embedding generation**
```typescript ```typescript
const id = await brain.addNoun("test content", 'content') const id = await brain.add("test content", { nounType: 'content' })
const item = await brain.get(id) const item = await brain.get(id)
console.log('Item:', item) // Should have metadata and vector console.log('Item:', item) // Should have metadata and vector
``` ```
@ -193,7 +193,8 @@ const brain = new BrainyData({
3. **Check data quality** 3. **Check data quality**
```typescript ```typescript
// Ensure consistent, descriptive content // Ensure consistent, descriptive content
await brain.addNoun("Domestic cat - small carnivorous mammal", 'content', { await brain.add("Domestic cat - small carnivorous mammal", {
nounType: 'content',
category: "animals", category: "animals",
subcategory: "pets" subcategory: "pets"
}) })
@ -250,7 +251,7 @@ const brain = new BrainyData({
// Process in batches instead of loading all at once // Process in batches instead of loading all at once
for (let i = 0; i < data.length; i += 100) { for (let i = 0; i < data.length; i += 100) {
const batch = data.slice(i, i + 100) const batch = data.slice(i, i + 100)
await Promise.all(batch.map(item => brain.addNoun(item, 'content'))) await Promise.all(batch.map(item => brain.add(item, { nounType: 'content' })))
} }
``` ```
@ -366,7 +367,7 @@ try {
const brain = new BrainyData() const brain = new BrainyData()
await brain.init() await brain.init()
const id = await brain.addNoun("health check", 'content') const id = await brain.add("health check", { nounType: 'content' })
const results = await brain.search("health") const results = await brain.search("health")
console.log('✅ Brainy is working correctly') console.log('✅ Brainy is working correctly')

View file

@ -29,7 +29,7 @@ const brainy = new BrainyData()
await brainy.init() await brainy.init()
// Add some data // Add some data
const personId = await brainy.addNoun('John Doe', { const personId = await brainy.add('John Doe', {
type: 'Person', type: 'Person',
role: 'CEO', role: 'CEO',
company: 'Acme Corp' company: 'Acme Corp'

View file

@ -20,6 +20,7 @@ export interface BrainyInterface<T = unknown> {
getNoun(id: string): Promise<unknown> getNoun(id: string): Promise<unknown>
/** /**
* @deprecated Use add() instead - it's smart by default now
* Add a noun (entity with vector and metadata) to the database * Add a noun (entity with vector and metadata) to the database
* @param data Text string or vector representation (will auto-embed strings) * @param data Text string or vector representation (will auto-embed strings)
* @param nounType Required noun type (one of 31 types) * @param nounType Required noun type (one of 31 types)
@ -37,6 +38,7 @@ export interface BrainyInterface<T = unknown> {
searchText(text: string, limit?: number): Promise<unknown[]> searchText(text: string, limit?: number): Promise<unknown[]>
/** /**
* @deprecated Use relate() instead
* Create a relationship (verb) between two entities * Create a relationship (verb) between two entities
* @param sourceId The ID of the source entity * @param sourceId The ID of the source entity
* @param targetId The ID of the target entity * @param targetId The ID of the target entity