chore: update README.md and docs with Brainy logo and enhanced formatting

Standardized documentation by adding a centered Brainy logo across README files, examples, and guides. Adjusted text formatting for consistency, improved alignment, and readability of feature descriptions and examples.
This commit is contained in:
David Snelling 2025-06-11 08:49:30 -07:00
parent 21ae491913
commit 0b7b3f947b
11 changed files with 739 additions and 655 deletions

View file

@ -1,11 +1,17 @@
<div align="center">
<img src="brainy.png" alt="Brainy Logo" width="200"/>
# Contributing to Soulcraft Brainy # Contributing to Soulcraft Brainy
</div>
Thank you for your interest in contributing to Soulcraft Brainy! This document provides guidelines and instructions for Thank you for your interest in contributing to Soulcraft Brainy! This document provides guidelines and instructions for
contributing to the project. contributing to the project.
## Commit Message Guidelines ## Commit Message Guidelines
When contributing to this project, please write clear and descriptive commit messages that explain the purpose of your changes. Good commit messages help maintainers understand your contributions and make the review process smoother. When contributing to this project, please write clear and descriptive commit messages that explain the purpose of your
changes. Good commit messages help maintainers understand your contributions and make the review process smoother.
### Best Practices ### Best Practices

334
README.md
View file

@ -1,14 +1,11 @@
<div align="center"> <div align="center">
# 🧠 Brainy <img src="brainy.png" alt="Brainy Logo" width="200"/>
[![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE) [![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)
[![Node.js](https://img.shields.io/badge/node-%3E%3D23.11.0-brightgreen.svg)](https://nodejs.org/) [![Node.js](https://img.shields.io/badge/node-%3E%3D23.11.0-brightgreen.svg)](https://nodejs.org/)
[![TypeScript](https://img.shields.io/badge/TypeScript-5.1.6-blue.svg)](https://www.typescriptlang.org/) [![TypeScript](https://img.shields.io/badge/TypeScript-5.1.6-blue.svg)](https://www.typescriptlang.org/)
[![npm package](https://img.shields.io/badge/npm-@soulcraft/brainy-blue)](https://www.npmjs.com/package/@soulcraft/brainy)
[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](CONTRIBUTING.md) [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](CONTRIBUTING.md)
[![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg)](https://github.com/prettier/prettier)
[![TensorFlow](https://img.shields.io/badge/TensorFlow-4.22.0-orange.svg)](https://www.tensorflow.org/)
[![Cartographer](https://img.shields.io/badge/Cartographer-Official%20Standard-brightgreen)](https://github.com/sodal-project/cartographer) [![Cartographer](https://img.shields.io/badge/Cartographer-Official%20Standard-brightgreen)](https://github.com/sodal-project/cartographer)
**A powerful, lightweight vector & graph database for browsers and Node.js** **A powerful, lightweight vector & graph database for browsers and Node.js**
@ -35,7 +32,8 @@ and connections.
- **Extensible Augmentations** - Customize and extend functionality with pluggable components (LEGO blocks for your - **Extensible Augmentations** - Customize and extend functionality with pluggable components (LEGO blocks for your
data!) data!)
- **Built-in Conduits** - Sync and scale across instances with WebSocket and WebRTC (your data's teleportation system!) - **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!) - **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 - **Adaptive Intelligence** - Automatically optimizes for your environment and usage patterns
- **Cross-Platform** - Works everywhere you do: browsers, Node.js, and server environments - **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 - **Persistent Storage** - Data persists across sessions and scales to any size (no memory loss here, even for
@ -180,20 +178,22 @@ Brainy uses a powerful augmentation system to extend functionality. Augmentation
- Enables advanced reasoning, inference, and logical operations - Enables advanced reasoning, inference, and logical operations
- Analyzes relationships between entities - Analyzes relationships between entities
- Creates and trains language models from graph data - Creates and trains language models from graph data
- Examples: - Examples:
- Inferring new connections between existing data - Inferring new connections between existing data
- Building custom LLMs from your nouns and verbs - Building custom LLMs from your nouns and verbs
4. **CONDUIT** 🔌 4. **CONDUIT** 🔌
- Establishes high-bandwidth channels for structured data exchange - Establishes high-bandwidth channels for structured data exchange
- Connects with external systems and syncs between Brainy instances - Connects with external systems and syncs between Brainy instances
- Two built-in iConduit augmentations for scaling out and syncing: - 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!) - **WebSocket iConduit** - Syncs data between browsers and servers (like a digital postal service with
- **WebRTC iConduit** - Direct peer-to-peer syncing between browsers (like telepathy for your data, no middleman required!) superpowers!)
- Examples: - **WebRTC iConduit** - Direct peer-to-peer syncing between browsers (like telepathy for your data, no middleman
- Integrating with third-party APIs required!)
- Syncing Brainy instances between browsers using WebSockets - Examples:
- Peer-to-peer syncing between browsers using WebRTC - Integrating with third-party APIs
- Syncing Brainy instances between browsers using WebSockets
- Peer-to-peer syncing between browsers using WebRTC
5. **ACTIVATION** 5. **ACTIVATION**
- Initiates actions, responses, or data manipulations - Initiates actions, responses, or data manipulations
@ -524,65 +524,65 @@ await db.deleteVerb(verbId)
### Working with LLM Models ### Working with LLM Models
```typescript ```typescript
import { createLLMAugmentations } from '@soulcraft/brainy' import {createLLMAugmentations} from '@soulcraft/brainy'
// Create LLM augmentations // Create LLM augmentations
const { cognition, activation } = await createLLMAugmentations() const {cognition, activation} = await createLLMAugmentations()
// Create a new LLM model // Create a new LLM model
const createResult = await cognition.createModel({ const createResult = await cognition.createModel({
name: 'my-model', name: 'my-model',
description: 'A simple LLM model trained on Brainy data', description: 'A simple LLM model trained on Brainy data',
modelType: 'simple', modelType: 'simple',
vocabSize: 5000, vocabSize: 5000,
embeddingDim: 64, embeddingDim: 64,
hiddenDim: 128, hiddenDim: 128,
numLayers: 1 numLayers: 1
}) })
const modelId = createResult.data.modelId const modelId = createResult.data.modelId
// Train the model // Train the model
const trainResult = await cognition.trainModel(modelId, { const trainResult = await cognition.trainModel(modelId, {
maxSamples: 100, maxSamples: 100,
validationSplit: 0.2, validationSplit: 0.2,
earlyStoppingPatience: 2 earlyStoppingPatience: 2
}) })
// Test the model // Test the model
const testResult = await cognition.testModel(modelId, { const testResult = await cognition.testModel(modelId, {
testSize: 20, testSize: 20,
generateSamples: true, generateSamples: true,
sampleCount: 3 sampleCount: 3
}) })
// Generate text with the model // Generate text with the model
const generateResult = await cognition.generateText(modelId, 'What is a', { const generateResult = await cognition.generateText(modelId, 'What is a', {
temperature: 0.7, temperature: 0.7,
topK: 5 topK: 5
}) })
// Export the model // Export the model
const exportResult = await cognition.exportModel(modelId, { const exportResult = await cognition.exportModel(modelId, {
format: 'json', format: 'json',
includeMetadata: true, includeMetadata: true,
includeVocab: true includeVocab: true
}) })
// Deploy the model // Deploy the model
const deployResult = await cognition.deployModel(modelId, { const deployResult = await cognition.deployModel(modelId, {
target: 'browser' target: 'browser'
}) })
// Using the augmentation pipeline // Using the augmentation pipeline
const pipelineResult = await augmentationPipeline.executeCognitionPipeline( const pipelineResult = await augmentationPipeline.executeCognitionPipeline(
'createModel', 'createModel',
[{ [{
name: 'pipeline-model', name: 'pipeline-model',
modelType: 'transformer', modelType: 'transformer',
numHeads: 2, numHeads: 2,
numLayers: 1 numLayers: 1
}] }]
) )
``` ```
@ -682,9 +682,11 @@ Brainy can be deployed as a standalone web service on various cloud platforms us
- **Google Cloud Run**: Deploy as a containerized service - **Google Cloud Run**: Deploy as a containerized service
- **Cloudflare Workers**: Deploy as a serverless function on the edge - **Cloudflare Workers**: Deploy as a serverless function on the edge
The cloud wrapper provides both RESTful and WebSocket APIs for all Brainy operations, enabling both request-response and real-time communication patterns. It supports multiple storage backends and can be configured via environment variables. The cloud wrapper provides both RESTful and WebSocket APIs for all Brainy operations, enabling both request-response and
real-time communication patterns. It supports multiple storage backends and can be configured via environment variables.
Key features of the cloud wrapper: Key features of the cloud wrapper:
- RESTful API for standard CRUD operations - RESTful API for standard CRUD operations
- WebSocket API for real-time updates and subscriptions - WebSocket API for real-time updates and subscriptions
- Support for multiple storage backends (Memory, FileSystem, S3) - Support for multiple storage backends (Memory, FileSystem, S3)
@ -695,7 +697,8 @@ To get started with cloud deployment, see the [Cloud Wrapper README](cloud-wrapp
## 🔗 Related Projects ## 🔗 Related Projects
- **[sodal-project cartographer](https://github.com/sodal-project/cartographer)** - The defacto standard for interacting with Brainy - **[sodal-project cartographer](https://github.com/sodal-project/cartographer)** - The defacto standard for interacting
with Brainy
## 📚 Examples ## 📚 Examples
@ -712,16 +715,19 @@ The repository includes several examples:
You can use the conduit augmentations to sync Brainy instances: You can use the conduit augmentations to sync Brainy instances:
- **WebSocket iConduit**: For syncing between browsers and servers, or between servers (like a digital postal service with superpowers!). WebSockets cannot be used for direct browser-to-browser communication without a server in the middle. - **WebSocket iConduit**: For syncing between browsers and servers, or between servers (like a digital postal service
- **WebRTC iConduit**: For direct peer-to-peer syncing between browsers (like telepathy for your data, no middleman required!). This is the recommended approach for browser-to-browser communication. with superpowers!). WebSockets cannot be used for direct browser-to-browser communication without a server in the
middle.
- **WebRTC iConduit**: For direct peer-to-peer syncing between browsers (like telepathy for your data, no middleman
required!). This is the recommended approach for browser-to-browser communication.
#### WebSocket Sync Example #### WebSocket Sync Example
```typescript ```typescript
import { import {
BrainyData, BrainyData,
augmentationPipeline, augmentationPipeline,
createConduitAugmentation createConduitAugmentation
} from '@soulcraft/brainy' } from '@soulcraft/brainy'
// Create and initialize the database // Create and initialize the database
@ -736,46 +742,46 @@ augmentationPipeline.register(wsConduit)
// Connect to another Brainy instance (server or browser) // Connect to another Brainy instance (server or browser)
const connectionResult = await augmentationPipeline.executeConduitPipeline( const connectionResult = await augmentationPipeline.executeConduitPipeline(
'establishConnection', 'establishConnection',
['wss://your-websocket-server.com/brainy-sync', { protocols: 'brainy-sync' }] ['wss://your-websocket-server.com/brainy-sync', {protocols: 'brainy-sync'}]
) )
if (connectionResult[0] && (await connectionResult[0]).success) { if (connectionResult[0] && (await connectionResult[0]).success) {
const connection = (await connectionResult[0]).data const connection = (await connectionResult[0]).data
// Read data from the remote instance // Read data from the remote instance
const readResult = await augmentationPipeline.executeConduitPipeline( const readResult = await augmentationPipeline.executeConduitPipeline(
'readData', 'readData',
[{ connectionId: connection.connectionId, query: { type: 'getAllNouns' } }] [{connectionId: connection.connectionId, query: {type: 'getAllNouns'}}]
) )
// Process and add the received data to the local instance // Process and add the received data to the local instance
if (readResult[0] && (await readResult[0]).success) { if (readResult[0] && (await readResult[0]).success) {
const remoteNouns = (await readResult[0]).data const remoteNouns = (await readResult[0]).data
for (const noun of remoteNouns) { for (const noun of remoteNouns) {
await db.add(noun.vector, noun.metadata) await db.add(noun.vector, noun.metadata)
}
} }
}
// Set up real-time sync by monitoring the stream // Set up real-time sync by monitoring the stream
await wsConduit.monitorStream(connection.connectionId, async (data) => { await wsConduit.monitorStream(connection.connectionId, async (data) => {
// Handle incoming data (e.g., new nouns, verbs, updates) // Handle incoming data (e.g., new nouns, verbs, updates)
if (data.type === 'newNoun') { if (data.type === 'newNoun') {
await db.add(data.vector, data.metadata) await db.add(data.vector, data.metadata)
} else if (data.type === 'newVerb') { } else if (data.type === 'newVerb') {
await db.addVerb(data.sourceId, data.targetId, data.vector, data.options) await db.addVerb(data.sourceId, data.targetId, data.vector, data.options)
} }
}) })
} }
``` ```
#### WebRTC Peer-to-Peer Sync Example #### WebRTC Peer-to-Peer Sync Example
```typescript ```typescript
import { import {
BrainyData, BrainyData,
augmentationPipeline, augmentationPipeline,
createConduitAugmentation createConduitAugmentation
} from '@soulcraft/brainy' } from '@soulcraft/brainy'
// Create and initialize the database // Create and initialize the database
@ -790,87 +796,88 @@ augmentationPipeline.register(webrtcConduit)
// Connect to a peer using a signaling server // Connect to a peer using a signaling server
const connectionResult = await augmentationPipeline.executeConduitPipeline( const connectionResult = await augmentationPipeline.executeConduitPipeline(
'establishConnection', 'establishConnection',
[ [
'peer-id-to-connect-to', 'peer-id-to-connect-to',
{ {
signalServerUrl: 'wss://your-signal-server.com', signalServerUrl: 'wss://your-signal-server.com',
localPeerId: 'my-peer-id', localPeerId: 'my-peer-id',
iceServers: [{ urls: 'stun:stun.l.google.com:19302' }] iceServers: [{urls: 'stun:stun.l.google.com:19302'}]
} }
] ]
) )
if (connectionResult[0] && (await connectionResult[0]).success) { if (connectionResult[0] && (await connectionResult[0]).success) {
const connection = (await connectionResult[0]).data const connection = (await connectionResult[0]).data
// Set up real-time sync by monitoring the stream // Set up real-time sync by monitoring the stream
await webrtcConduit.monitorStream(connection.connectionId, async (data) => { await webrtcConduit.monitorStream(connection.connectionId, async (data) => {
// Handle incoming data (e.g., new nouns, verbs, updates) // Handle incoming data (e.g., new nouns, verbs, updates)
if (data.type === 'newNoun') { if (data.type === 'newNoun') {
await db.add(data.vector, data.metadata) await db.add(data.vector, data.metadata)
} else if (data.type === 'newVerb') { } else if (data.type === 'newVerb') {
await db.addVerb(data.sourceId, data.targetId, data.vector, data.options) await db.addVerb(data.sourceId, data.targetId, data.vector, data.options)
} }
}) })
// When adding new data locally, also send to the peer // When adding new data locally, also send to the peer
const nounId = await db.add("New data to sync", { noun: "Thing" }) const nounId = await db.add("New data to sync", {noun: "Thing"})
// Send the new noun to the peer // Send the new noun to the peer
await augmentationPipeline.executeConduitPipeline( await augmentationPipeline.executeConduitPipeline(
'writeData', 'writeData',
[ [
{ {
connectionId: connection.connectionId, connectionId: connection.connectionId,
data: { data: {
type: 'newNoun', type: 'newNoun',
id: nounId, id: nounId,
vector: (await db.get(nounId)).vector, vector: (await db.get(nounId)).vector,
metadata: (await db.get(nounId)).metadata metadata: (await db.get(nounId)).metadata
} }
} }
] ]
) )
} }
``` ```
#### Browser-Server Search Example #### Browser-Server Search Example
Brainy supports searching a server-hosted instance from a browser, storing results locally, and performing further searches against the local instance: Brainy supports searching a server-hosted instance from a browser, storing results locally, and performing further
searches against the local instance:
```typescript ```typescript
import { BrainyData } from '@soulcraft/brainy' import {BrainyData} from '@soulcraft/brainy'
// Create and initialize the database with remote server configuration // Create and initialize the database with remote server configuration
const db = new BrainyData({ const db = new BrainyData({
remoteServer: { remoteServer: {
url: 'wss://your-brainy-server.com/ws', url: 'wss://your-brainy-server.com/ws',
protocols: 'brainy-sync', protocols: 'brainy-sync',
autoConnect: true // Connect automatically during initialization autoConnect: true // Connect automatically during initialization
} }
}) })
await db.init() await db.init()
// Or connect manually after initialization // Or connect manually after initialization
if (!db.isConnectedToRemoteServer()) { if (!db.isConnectedToRemoteServer()) {
await db.connectToRemoteServer('wss://your-brainy-server.com/ws', 'brainy-sync') await db.connectToRemoteServer('wss://your-brainy-server.com/ws', 'brainy-sync')
} }
// Search the remote server (results are stored locally) // Search the remote server (results are stored locally)
const remoteResults = await db.searchText('machine learning', 5, { searchMode: 'remote' }) const remoteResults = await db.searchText('machine learning', 5, {searchMode: 'remote'})
// Search the local database (includes previously stored results) // Search the local database (includes previously stored results)
const localResults = await db.searchText('machine learning', 5, { searchMode: 'local' }) const localResults = await db.searchText('machine learning', 5, {searchMode: 'local'})
// Perform a combined search (local first, then remote if needed) // Perform a combined search (local first, then remote if needed)
const combinedResults = await db.searchText('neural networks', 5, { searchMode: 'combined' }) const combinedResults = await db.searchText('neural networks', 5, {searchMode: 'combined'})
// Add data to both local and remote instances // Add data to both local and remote instances
const id = await db.addToBoth('Deep learning is a subset of machine learning', { const id = await db.addToBoth('Deep learning is a subset of machine learning', {
noun: 'Concept', noun: 'Concept',
category: 'AI', category: 'AI',
tags: ['deep learning', 'neural networks'] tags: ['deep learning', 'neural networks']
}) })
// Clean up when done // Clean up when done
@ -890,51 +897,52 @@ For a complete example with HTML interface, see the [browser-server-search examp
Brainy follows a specific code style to maintain consistency throughout the codebase: Brainy follows a specific code style to maintain consistency throughout the codebase:
1. **No Semicolons**: All code in the project should avoid using semicolons wherever possible. This applies to: 1. **No Semicolons**: All code in the project should avoid using semicolons wherever possible. This applies to:
- Source code files (.ts, .js) - Source code files (.ts, .js)
- Generated code - Generated code
- Code examples in documentation - Code examples in documentation
- Templates and snippets - Templates and snippets
2. **Formatting**: The project uses Prettier for code formatting with the following settings: 2. **Formatting**: The project uses Prettier for code formatting with the following settings:
- No semicolons (`"semi": false`) - No semicolons (`"semi": false`)
- Single quotes for strings (`"singleQuote": true`) - Single quotes for strings (`"singleQuote": true`)
- 2-space indentation (`"tabWidth": 2`) - 2-space indentation (`"tabWidth": 2`)
- Always use parentheses around arrow function parameters (`"arrowParens": "always"`) - Always use parentheses around arrow function parameters (`"arrowParens": "always"`)
- Place the closing bracket of JSX elements on the same line (`"bracketSameLine": true`) - Place the closing bracket of JSX elements on the same line (`"bracketSameLine": true`)
- Add spaces between brackets and object literals (`"bracketSpacing": true`) - Add spaces between brackets and object literals (`"bracketSpacing": true`)
- Line width of 80 characters (`"printWidth": 80`) - Line width of 80 characters (`"printWidth": 80`)
- No trailing commas (`"trailingComma": "none"`) - No trailing commas (`"trailingComma": "none"`)
- Use spaces instead of tabs (`"useTabs": false`) - Use spaces instead of tabs (`"useTabs": false`)
3. **Linting**: ESLint is configured with the following rules: 3. **Linting**: ESLint is configured with the following rules:
- No semicolons: - No semicolons:
```json ```json
"semi": ["error", "never"], "semi": ["error", "never"],
"@typescript-eslint/semi": ["error", "never"] "@typescript-eslint/semi": ["error", "never"]
``` ```
- Unused variables handling: - Unused variables handling:
```json ```json
"no-unused-vars": "off", "no-unused-vars": "off",
"@typescript-eslint/no-unused-vars": ["warn", { "@typescript-eslint/no-unused-vars": ["warn", {
"args": "after-used", "args": "after-used",
"argsIgnorePattern": "^_" "argsIgnorePattern": "^_"
}] }]
``` ```
- Extends recommended ESLint and TypeScript ESLint configurations - Extends recommended ESLint and TypeScript ESLint configurations
4. **TypeScript Configuration**: 4. **TypeScript Configuration**:
- Strict type checking enabled (`"strict": true`) - Strict type checking enabled (`"strict": true`)
- Consistent casing in file names enforced (`"forceConsistentCasingInFileNames": true`) - Consistent casing in file names enforced (`"forceConsistentCasingInFileNames": true`)
- ES2020 target with Node.js module system - ES2020 target with Node.js module system
- Source maps generated for debugging - Source maps generated for debugging
5. **Commit Messages**: 5. **Commit Messages**:
- Use the imperative mood ("Add feature" not "Added feature") - Use the imperative mood ("Add feature" not "Added feature")
- Keep the first line concise (under 50 characters) - Keep the first line concise (under 50 characters)
- Reference issues and pull requests where appropriate - Reference issues and pull requests where appropriate
- Provide detailed explanations in the commit body when necessary - Provide detailed explanations in the commit body when necessary
When contributing to the project, please ensure your code follows these guidelines. The project's CI/CD pipeline will automatically check for style violations. When contributing to the project, please ensure your code follows these guidelines. The project's CI/CD pipeline will
automatically check for style violations.
### Development Workflow ### Development Workflow

BIN
brainy.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 MiB

View file

@ -1,4 +1,8 @@
<div align="center">
<img src="../brainy.png" alt="Brainy Logo" width="200"/>
# Brainy Cloud Wrapper # Brainy Cloud Wrapper
</div>
A standalone web service wrapper for the [Brainy](https://github.com/soulcraft/brainy) vector graph database. This wrapper allows you to deploy Brainy as a RESTful API service on various cloud platforms including AWS, Google Cloud, and Cloudflare. A standalone web service wrapper for the [Brainy](https://github.com/soulcraft/brainy) vector graph database. This wrapper allows you to deploy Brainy as a RESTful API service on various cloud platforms including AWS, Google Cloud, and Cloudflare.

View file

@ -1,4 +1,8 @@
<div align="center">
<img src="../brainy.png" alt="Brainy Logo" width="200"/>
# Build-Time Augmentation Registration # Build-Time Augmentation Registration
</div>
This document explains how to register custom augmentations at build time using the Brainy library's augmentation This document explains how to register custom augmentations at build time using the Brainy library's augmentation
registry system. registry system.

View file

@ -1,4 +1,8 @@
<div align="center">
<img src="../brainy.png" alt="Brainy Logo" width="200"/>
# LLM Augmentation for Brainy # LLM Augmentation for Brainy
</div>
This document describes the LLM (Language Learning Model) augmentation for Brainy, which enables creating, training, testing, exporting, and deploying language models from the data in Brainy's graph database. This document describes the LLM (Language Learning Model) augmentation for Brainy, which enables creating, training, testing, exporting, and deploying language models from the data in Brainy's graph database.

View file

@ -1,4 +1,8 @@
<div align="center">
<img src="../brainy.png" alt="Brainy Logo" width="200"/>
# Brainy Examples # Brainy Examples
</div>
This directory contains examples demonstrating various features and use cases of the Brainy vector graph database. This directory contains examples demonstrating various features and use cases of the Brainy vector graph database.

View file

@ -1,4 +1,8 @@
<div align="center">
<img src="../../brainy.png" alt="Brainy Logo" width="200"/>
# Brainy Browser-Server Search Example # Brainy Browser-Server Search Example
</div>
This example demonstrates how to use Brainy in a browser, call a server-hosted version for search, store the results locally, and then perform further searches against the local instance. This example demonstrates how to use Brainy in a browser, call a server-hosted version for search, store the results locally, and then perform further searches against the local instance.

View file

@ -59,19 +59,22 @@
</style> </style>
</head> </head>
<body> <body>
<h1>Brainy Browser-Server Search Example</h1> <div style="display: flex; align-items: center; margin-bottom: 20px;">
<img src="../../brainy.png" alt="Brainy Logo" width="100" style="margin-right: 20px;"/>
<h1>Brainy Browser-Server Search Example</h1>
</div>
<p> <p>
This example demonstrates how to use Brainy in a browser, call a server-hosted version for search, This example demonstrates how to use Brainy in a browser, call a server-hosted version for search,
store the results locally, and then perform further searches against the local instance. store the results locally, and then perform further searches against the local instance.
</p> </p>
<div> <div>
<h2>Server URL</h2> <h2>Server URL</h2>
<input type="text" id="serverUrl" value="wss://your-brainy-server.com/ws" placeholder="WebSocket URL of your Brainy server"> <input type="text" id="serverUrl" value="wss://your-brainy-server.com/ws" placeholder="WebSocket URL of your Brainy server">
<button id="connectBtn">Connect</button> <button id="connectBtn">Connect</button>
</div> </div>
<div> <div>
<h2>Search</h2> <h2>Search</h2>
<input type="text" id="searchQuery" placeholder="Enter search query"> <input type="text" id="searchQuery" placeholder="Enter search query">
@ -79,28 +82,28 @@
<button id="searchLocalBtn">Search Local</button> <button id="searchLocalBtn">Search Local</button>
<button id="searchCombinedBtn">Search Combined</button> <button id="searchCombinedBtn">Search Combined</button>
</div> </div>
<div> <div>
<h2>Add Data</h2> <h2>Add Data</h2>
<input type="text" id="addData" placeholder="Enter text to add"> <input type="text" id="addData" placeholder="Enter text to add">
<button id="addBtn">Add to Both</button> <button id="addBtn">Add to Both</button>
</div> </div>
<div class="result-container"> <div class="result-container">
<h2>Results</h2> <h2>Results</h2>
<pre id="results">Connect to a server to begin...</pre> <pre id="results">Connect to a server to begin...</pre>
</div> </div>
<div class="log" id="log"></div> <div class="log" id="log"></div>
<!-- Import the Brainy library --> <!-- Import the Brainy library -->
<script type="module"> <script type="module">
// Import the BrainyServerSearch class // Import the BrainyServerSearch class
import { BrainyServerSearch } from './index.js'; import { BrainyServerSearch } from './index.js';
// Global variables // Global variables
let brainySearch = null; let brainySearch = null;
// DOM elements // DOM elements
const serverUrlInput = document.getElementById('serverUrl'); const serverUrlInput = document.getElementById('serverUrl');
const connectBtn = document.getElementById('connectBtn'); const connectBtn = document.getElementById('connectBtn');
@ -112,7 +115,7 @@
const addBtn = document.getElementById('addBtn'); const addBtn = document.getElementById('addBtn');
const resultsElement = document.getElementById('results'); const resultsElement = document.getElementById('results');
const logElement = document.getElementById('log'); const logElement = document.getElementById('log');
// Helper functions // Helper functions
function log(message, isError = false) { function log(message, isError = false) {
const div = document.createElement('div'); const div = document.createElement('div');
@ -123,11 +126,11 @@
logElement.appendChild(div); logElement.appendChild(div);
logElement.scrollTop = logElement.scrollHeight; logElement.scrollTop = logElement.scrollHeight;
} }
function displayResults(results) { function displayResults(results) {
resultsElement.textContent = JSON.stringify(results, null, 2); resultsElement.textContent = JSON.stringify(results, null, 2);
} }
// Event handlers // Event handlers
connectBtn.addEventListener('click', async () => { connectBtn.addEventListener('click', async () => {
const serverUrl = serverUrlInput.value.trim(); const serverUrl = serverUrlInput.value.trim();
@ -135,7 +138,7 @@
log('Please enter a server URL', true); log('Please enter a server URL', true);
return; return;
} }
try { try {
log(`Connecting to ${serverUrl}...`); log(`Connecting to ${serverUrl}...`);
brainySearch = new BrainyServerSearch(serverUrl); brainySearch = new BrainyServerSearch(serverUrl);
@ -147,19 +150,19 @@
displayResults({ error: error.message }); displayResults({ error: error.message });
} }
}); });
searchServerBtn.addEventListener('click', async () => { searchServerBtn.addEventListener('click', async () => {
if (!brainySearch) { if (!brainySearch) {
log('Please connect to a server first', true); log('Please connect to a server first', true);
return; return;
} }
const query = searchQueryInput.value.trim(); const query = searchQueryInput.value.trim();
if (!query) { if (!query) {
log('Please enter a search query', true); log('Please enter a search query', true);
return; return;
} }
try { try {
log(`Searching server for "${query}"...`); log(`Searching server for "${query}"...`);
const results = await brainySearch.searchServer(query, 5); const results = await brainySearch.searchServer(query, 5);
@ -170,19 +173,19 @@
displayResults({ error: error.message }); displayResults({ error: error.message });
} }
}); });
searchLocalBtn.addEventListener('click', async () => { searchLocalBtn.addEventListener('click', async () => {
if (!brainySearch) { if (!brainySearch) {
log('Please connect to a server first', true); log('Please connect to a server first', true);
return; return;
} }
const query = searchQueryInput.value.trim(); const query = searchQueryInput.value.trim();
if (!query) { if (!query) {
log('Please enter a search query', true); log('Please enter a search query', true);
return; return;
} }
try { try {
log(`Searching local database for "${query}"...`); log(`Searching local database for "${query}"...`);
const results = await brainySearch.searchLocal(query, 5); const results = await brainySearch.searchLocal(query, 5);
@ -193,19 +196,19 @@
displayResults({ error: error.message }); displayResults({ error: error.message });
} }
}); });
searchCombinedBtn.addEventListener('click', async () => { searchCombinedBtn.addEventListener('click', async () => {
if (!brainySearch) { if (!brainySearch) {
log('Please connect to a server first', true); log('Please connect to a server first', true);
return; return;
} }
const query = searchQueryInput.value.trim(); const query = searchQueryInput.value.trim();
if (!query) { if (!query) {
log('Please enter a search query', true); log('Please enter a search query', true);
return; return;
} }
try { try {
log(`Performing combined search for "${query}"...`); log(`Performing combined search for "${query}"...`);
const results = await brainySearch.searchCombined(query, 5); const results = await brainySearch.searchCombined(query, 5);
@ -216,19 +219,19 @@
displayResults({ error: error.message }); displayResults({ error: error.message });
} }
}); });
addBtn.addEventListener('click', async () => { addBtn.addEventListener('click', async () => {
if (!brainySearch) { if (!brainySearch) {
log('Please connect to a server first', true); log('Please connect to a server first', true);
return; return;
} }
const data = addDataInput.value.trim(); const data = addDataInput.value.trim();
if (!data) { if (!data) {
log('Please enter data to add', true); log('Please enter data to add', true);
return; return;
} }
try { try {
log(`Adding data: "${data}"...`); log(`Adding data: "${data}"...`);
const id = await brainySearch.add(data, { const id = await brainySearch.add(data, {
@ -243,7 +246,7 @@
displayResults({ error: error.message }); displayResults({ error: error.message });
} }
}); });
// Initial log // Initial log
log('Ready to connect to a Brainy server'); log('Ready to connect to a Brainy server');
</script> </script>

File diff suppressed because it is too large Load diff

View file

@ -1,4 +1,8 @@
<div align="center">
<img src="../../brainy.png" alt="Brainy Logo" width="200"/>
# Brainy Augmentations # Brainy Augmentations
</div>
This directory contains the augmentation implementations for Brainy. Augmentations are pluggable components that extend Brainy's functionality in various ways. This directory contains the augmentation implementations for Brainy. Augmentations are pluggable components that extend Brainy's functionality in various ways.
@ -191,31 +195,31 @@ class MyCustomActivation implements IActivationAugmentation {
readonly name = 'my-custom-activation' readonly name = 'my-custom-activation'
readonly description = 'My custom activation augmentation' readonly description = 'My custom activation augmentation'
enabled = true enabled = true
getType(): AugmentationType { getType(): AugmentationType {
return AugmentationType.ACTIVATION return AugmentationType.ACTIVATION
} }
async initialize(): Promise<void> { async initialize(): Promise<void> {
// Initialization code // Initialization code
} }
async shutDown(): Promise<void> { async shutDown(): Promise<void> {
// Cleanup code // Cleanup code
} }
async getStatus(): Promise<'active' | 'inactive' | 'error'> { async getStatus(): Promise<'active' | 'inactive' | 'error'> {
return 'active' return 'active'
} }
triggerAction(actionName: string, parameters?: Record<string, unknown>): AugmentationResponse<unknown> { triggerAction(actionName: string, parameters?: Record<string, unknown>): AugmentationResponse<unknown> {
// Implementation // Implementation
} }
generateOutput(knowledgeId: string, format: string): AugmentationResponse<string | Record<string, unknown>> { generateOutput(knowledgeId: string, format: string): AugmentationResponse<string | Record<string, unknown>> {
// Implementation // Implementation
} }
interactExternal(systemId: string, payload: Record<string, unknown>): AugmentationResponse<unknown> { interactExternal(systemId: string, payload: Record<string, unknown>): AugmentationResponse<unknown> {
// Implementation // Implementation
} }