[](LICENSE)
[](https://nodejs.org/)
[](https://www.typescriptlang.org/)
[](CONTRIBUTING.md)
[](https://github.com/sodal-project/cartographer)
**A powerful, lightweight vector & graph database for browsers and Node.js**
## β¨ Overview
Say hello to Brainy, your new favorite data sidekick! π Brainy combines the power of vector search with graph
relationships in a lightweight, cross-platform database that's as smart as it is fun to use. Whether you're building AI
applications, recommendation systems, or knowledge graphs, Brainy provides the tools you need to store, connect, and
retrieve your data intelligently.
What makes Brainy special? It intelligently adapts to you and your environment! Like a chameleon with a PhD, Brainy
automatically detects your platform, adjusts its storage strategy, and optimizes performance based on your usage
patterns. The more you use it, the smarter it gets - learning from your data to provide increasingly relevant results
and connections.
### π Key Features
- **Vector Search** - Find semantically similar content using embeddings (like having ESP for your data!)
- **Graph Relationships** - Connect data with meaningful relationships (your data's social network)
- **Streaming Pipeline** - Process data in real-time as it flows through the system (like a data waterslide!)
- **Extensible Augmentations** - Customize and extend functionality with pluggable components (LEGO blocks for your
data!)
- **Built-in Conduits** - Sync and scale across instances with WebSocket and WebRTC (your data's teleportation system!)
- **LLM Creation & Training** - Build, train, and deploy language models from your graph data (your own personal AI
factory!)
- **Adaptive Intelligence** - Automatically optimizes for your environment and usage patterns
- **Cross-Platform** - Works everywhere you do: browsers, Node.js, and server environments
- **Persistent Storage** - Data persists across sessions and scales to any size (no memory loss here, even for
elephant-sized data!)
- **TypeScript Support** - Fully typed API with generics (for those who like their code tidy)
- **CLI Tools** - Powerful command-line interface for data management (command line wizardry)
## π What Can You Build? (The Fun Stuff!)
- **Semantic Search Engines** - Find content based on meaning, not just keywords (mind-reading for your data!)
- **Recommendation Systems** - Suggest similar items based on vector similarity (like a friend who really gets your
taste)
- **Knowledge Graphs** - Build connected data structures with relationships (your data's family tree)
- **AI Applications** - Store and retrieve embeddings for machine learning models (brain food for your AI)
- **Custom Language Models** - Create, train, and deploy LLMs from your graph data (your personal GPT factory!)
- **Data Organization Tools** - Automatically categorize and connect related information (like having a librarian in
your code)
- **Adaptive Experiences** - Create applications that learn and evolve with your users (digital chameleons!)
## π§ Installation
Due to a dependency conflict between TensorFlow.js packages, use the `--legacy-peer-deps` flag when installing:
```bash
npm install @soulcraft/brainy --legacy-peer-deps
```
## π Quick Start
```typescript
import {BrainyData, NounType, VerbType} from '@soulcraft/brainy'
// Create and initialize the database
const db = new BrainyData()
await db.init()
// Add data (automatically converted to vectors)
const catId = await db.add("Cats are independent pets", {
noun: NounType.Thing,
category: 'animal'
})
const dogId = await db.add("Dogs are loyal companions", {
noun: NounType.Thing,
category: 'animal'
})
// Search for similar items
const results = await db.searchText("feline pets", 2)
console.log(results)
// Returns items similar to "feline pets" with similarity scores
// Add a relationship between items
await db.addVerb(catId, dogId, {
verb: VerbType.RelatedTo,
description: 'Both are common household pets'
})
```
## π§© How It Works (The Magic Behind the Curtain)
Brainy combines four key technologies to create its adaptive intelligence:
1. **Vector Embeddings** - Converts data (text, images, etc.) into numerical vectors that capture semantic meaning (
translating your data into brain-speak!)
2. **HNSW Algorithm** - Enables fast similarity search through a hierarchical graph structure (like a super-efficient
treasure map for your data)
3. **Adaptive Environment Detection** - Automatically senses your platform and optimizes accordingly:
- Adjusts performance parameters based on available resources
- Learns from query patterns to optimize future searches
- Tunes itself for your specific use cases the more you use it
4. **Intelligent Storage Selection** - Uses the best available storage option for your environment, scaling effortlessly
to any data size (from bytes to petabytes!):
- Browser: Origin Private File System (OPFS)
- Node.js: File system
- Server: S3-compatible storage (optional)
- Fallback: In-memory storage
- Automatically migrates between storage types as needed!
## π The Brainy Pipeline (Data's Wild Ride!)
Brainy's data processing pipeline transforms raw data into searchable, connected knowledge that gets smarter over time.
Here's how the magic happens:
```
Raw Data β Embedding β Vector Storage β Graph Connections β Adaptive Learning β Query & Retrieval
```
Each time data flows through this pipeline, Brainy learns a little more about your usage patterns and environment,
making future operations even faster and more relevant!
### π Pipeline Stages (The Journey of Your Data)
1. **Data Ingestion** π½οΈ
- Raw text or pre-computed vectors enter the pipeline (dinner time for data!)
- Data is validated and prepared for processing (washing hands before eating)
2. **Embedding Generation** π§
- Text is transformed into numerical vectors using embedding models (language β math magic)
- Choose between TensorFlow Universal Sentence Encoder (high quality) or Simple Embedding (faster)
- Custom embedding functions can be plugged in for specialized domains (bring your own secret sauce)
3. **Vector Indexing** π
- Vectors are indexed using the HNSW algorithm (filing your data in the brain cabinet)
- Hierarchical structure enables lightning-fast similarity search (express lanes for your queries)
- Configurable parameters for precision vs. performance tradeoffs (dial in your perfect balance)
4. **Graph Construction** πΈοΈ
- Nouns (entities) become nodes in the knowledge graph (data gets its own social network)
- Verbs (relationships) connect related entities (making friends and connections)
- Typed relationships add semantic meaning to connections (not just friends, but BFFs)
5. **Adaptive Learning** π±
- Analyzes usage patterns to optimize future operations (gets to know your habits)
- Tunes performance parameters based on your environment (adapts to your digital home)
- Adjusts search strategies based on query history (learns what you're really looking for)
- Becomes more efficient and relevant the more you use it (like a good friendship)
6. **Intelligent Storage** πΎ
- Data is saved using the optimal storage for your environment (finds the coziest home for your data)
- Automatic selection between OPFS, filesystem, S3, or memory (no manual configuration needed!)
- Migrates between storage types as your application's needs evolve (moves houses without you noticing)
- Scales effortlessly from tiny datasets to massive data collections (from ant-sized to elephant-sized data, no
problem!)
- Configurable storage adapters for custom persistence needs (design your own dream data home)
### π§© Augmentation Types
Brainy uses a powerful augmentation system to extend functionality. Augmentations are processed in the following order:
1. **SENSE** ποΈ
- Ingests and processes raw, unstructured data into nouns and verbs
- Handles text, images, audio streams, and other input formats
- Example: Converting raw text into structured entities
2. **MEMORY** πΎ
- Provides storage capabilities for data in different formats
- Manages persistence across sessions
- Example: Storing vectors in OPFS or filesystem
3. **COGNITION** π§
- Enables advanced reasoning, inference, and logical operations
- Analyzes relationships between entities
- Creates and trains language models from graph data
- Examples:
- Inferring new connections between existing data
- Building custom LLMs from your nouns and verbs
4. **CONDUIT** π
- Establishes high-bandwidth channels for structured data exchange
- Connects with external systems and syncs between Brainy instances
- Two built-in iConduit augmentations for scaling out and syncing:
- **WebSocket iConduit** - Syncs data between browsers and servers (like a digital postal service with
superpowers!)
- **WebRTC iConduit** - Direct peer-to-peer syncing between browsers (like telepathy for your data, no middleman
required!)
- Examples:
- Integrating with third-party APIs
- Syncing Brainy instances between browsers using WebSockets
- Peer-to-peer syncing between browsers using WebRTC
5. **ACTIVATION** β‘
- Initiates actions, responses, or data manipulations
- Triggers events based on data changes
- Example: Sending notifications when new data is processed
6. **PERCEPTION** π
- Interprets, contextualizes, and visualizes identified nouns and verbs
- Creates meaningful representations of data
- Example: Generating visualizations of graph relationships
7. **DIALOG** π¬
- Facilitates natural language understanding and generation
- Enables conversational interactions
- Example: Processing user queries and generating responses
8. **WEBSOCKET** π
- Enables real-time communication via WebSockets
- Can be combined with other augmentation types
- Example: Streaming data processing in real-time
### π Streaming Data Support
Brainy's pipeline is designed to handle streaming data efficiently:
1. **WebSocket Integration** π
- Built-in support for WebSocket connections
- Process data as it arrives without blocking
- Example: `setupWebSocketPipeline(url, dataType, options)`
2. **Asynchronous Processing** β‘
- Non-blocking architecture for real-time data handling
- Parallel processing of incoming streams
- Example: `createWebSocketHandler(connection, dataType, options)`
3. **Event-Based Architecture** π‘
- Augmentations can listen to data feeds and streams
- Real-time updates propagate through the pipeline
- Example: `listenToFeed(feedUrl, callback)`
4. **Threaded Execution** π§΅
- Optional multi-threading for high-performance streaming
- Configurable execution modes (SEQUENTIAL, PARALLEL, THREADED)
- Example: `executeTypedPipeline(augmentations, method, args, { mode: ExecutionMode.THREADED })`
### πββοΈ Running the Pipeline
The pipeline runs automatically when you:
```typescript
// Add data (runs embedding β indexing β storage)
const id = await db.add("Your text data here", {metadata})
// Search (runs embedding β similarity search)
const results = await db.searchText("Your query here", 5)
// Connect entities (runs graph construction β storage)
await db.addVerb(sourceId, targetId, {verb: VerbType.RelatedTo})
```
Using the CLI:
```bash
# Add data through the CLI pipeline
brainy add "Your text data here" '{"noun":"Thing"}'
# Search through the CLI pipeline
brainy search "Your query here" --limit 5
# Connect entities through the CLI
brainy addVerb