# BZZZ SDK Examples This directory contains comprehensive examples demonstrating the BZZZ SDK across multiple programming languages. These examples show real-world usage patterns, best practices, and advanced integration techniques. ## Quick Start Choose your preferred language and follow the setup instructions: - **Go**: [Go Examples](#go-examples) - **Python**: [Python Examples](#python-examples) - **JavaScript/Node.js**: [JavaScript Examples](#javascript-examples) - **Rust**: [Rust Examples](#rust-examples) ## Example Categories ### Basic Operations - Client initialization and connection - Status checks and peer discovery - Basic decision publishing and querying ### Real-time Operations - Event streaming and processing - Live decision monitoring - System health tracking ### Cryptographic Operations - Age encryption/decryption - Key management and validation - Role-based access control ### Advanced Integrations - Collaborative workflows - Performance monitoring - Custom agent implementations ## Go Examples ### Prerequisites ```bash # Install Go 1.21 or later go version # Initialize module (if creating new project) go mod init your-project go get github.com/anthonyrawlins/bzzz/sdk ``` ### Examples #### 1. Simple Client (`go/simple-client.go`) **Purpose**: Basic BZZZ client operations **Features**: - Client initialization and connection - Status and peer information - Simple decision publishing - Recent decision querying **Run**: ```bash cd examples/sdk/go go run simple-client.go ``` **Expected Output**: ``` 🚀 BZZZ SDK Simple Client Example ✅ Connected to BZZZ node Node ID: QmYourNodeID Agent ID: simple-client Role: backend_developer Authority Level: suggestion ... ``` #### 2. Event Streaming (`go/event-streaming.go`) **Purpose**: Real-time event processing **Features**: - System event subscription - Decision stream monitoring - Election event tracking - Graceful shutdown handling **Run**: ```bash cd examples/sdk/go go run event-streaming.go ``` **Use Case**: Monitoring dashboards, real-time notifications, event-driven architectures #### 3. Crypto Operations (`go/crypto-operations.go`) **Purpose**: Comprehensive cryptographic operations **Features**: - Age encryption testing - Role-based encryption/decryption - Multi-role encryption - Key generation and validation - Permission checking **Run**: ```bash cd examples/sdk/go go run crypto-operations.go ``` **Security Note**: Never log private keys in production. These examples are for demonstration only. ### Integration Patterns **Service Integration**: ```go // Embed BZZZ client in your service type MyService struct { bzzz *bzzz.Client // ... other fields } func NewMyService() *MyService { client, err := bzzz.NewClient(bzzz.Config{ Endpoint: os.Getenv("BZZZ_ENDPOINT"), Role: os.Getenv("BZZZ_ROLE"), }) // handle error return &MyService{bzzz: client} } ``` ## Python Examples ### Prerequisites ```bash # Install Python 3.8 or later python3 --version # Install BZZZ SDK pip install bzzz-sdk # Or for development pip install -e git+https://github.com/anthonyrawlins/bzzz-sdk-python.git#egg=bzzz-sdk ``` ### Examples #### 1. Async Client (`python/async_client.py`) **Purpose**: Asynchronous Python client operations **Features**: - Async/await patterns - Comprehensive error handling - Event streaming - Collaborative workflows - Performance demonstrations **Run**: ```bash cd examples/sdk/python python3 async_client.py ``` **Key Features**: - **Async Operations**: All network calls are non-blocking - **Error Handling**: Comprehensive exception handling - **Event Processing**: Real-time event streaming - **Crypto Operations**: Age encryption with Python integration - **Collaborative Workflows**: Multi-agent coordination examples **Usage in Your App**: ```python import asyncio from bzzz_sdk import BzzzClient async def your_application(): client = BzzzClient( endpoint="http://localhost:8080", role="your_role" ) # Your application logic status = await client.get_status() print(f"Connected as {status.agent_id}") await client.close() asyncio.run(your_application()) ``` ## JavaScript Examples ### Prerequisites ```bash # Install Node.js 16 or later node --version # Install BZZZ SDK npm install bzzz-sdk # Or yarn yarn add bzzz-sdk ``` ### Examples #### 1. Collaborative Agent (`javascript/collaborative-agent.js`) **Purpose**: Advanced collaborative agent implementation **Features**: - Event-driven collaboration - Autonomous task processing - Real-time coordination - Background job processing - Graceful shutdown **Run**: ```bash cd examples/sdk/javascript npm install # Install dependencies if needed node collaborative-agent.js ``` **Key Architecture**: - **Event-Driven**: Uses Node.js EventEmitter for internal coordination - **Collaborative**: Automatically detects collaboration opportunities - **Autonomous**: Performs independent tasks while monitoring for collaboration - **Production-Ready**: Includes error handling, logging, and graceful shutdown **Integration Example**: ```javascript const CollaborativeAgent = require('./collaborative-agent'); const agent = new CollaborativeAgent({ role: 'your_role', agentId: 'your-agent-id', endpoint: process.env.BZZZ_ENDPOINT }); // Custom event handlers agent.on('collaboration_started', (collaboration) => { console.log(`Started collaboration: ${collaboration.id}`); }); agent.initialize().then(() => { return agent.start(); }); ``` ## Rust Examples ### Prerequisites ```bash # Install Rust 1.70 or later rustc --version # Add to Cargo.toml [dependencies] bzzz-sdk = "2.0" tokio = { version = "1.0", features = ["full"] } tracing = "0.1" tracing-subscriber = "0.3" serde = { version = "1.0", features = ["derive"] } ``` ### Examples #### 1. Performance Monitor (`rust/performance-monitor.rs`) **Purpose**: High-performance system monitoring **Features**: - Concurrent metrics collection - Performance trend analysis - System health assessment - Alert generation - Efficient data processing **Run**: ```bash cd examples/sdk/rust cargo run --bin performance-monitor ``` **Architecture Highlights**: - **Async/Concurrent**: Uses Tokio for high-performance async operations - **Memory Efficient**: Bounded collections with retention policies - **Type Safe**: Full Rust type safety with serde serialization - **Production Ready**: Comprehensive error handling and logging **Performance Features**: - **Metrics Collection**: System metrics every 10 seconds - **Trend Analysis**: Statistical analysis of performance trends - **Health Scoring**: Composite health scores with component breakdown - **Alert System**: Configurable thresholds with alert generation ## Common Patterns ### Client Initialization All examples follow similar initialization patterns: **Go**: ```go client, err := bzzz.NewClient(bzzz.Config{ Endpoint: "http://localhost:8080", Role: "your_role", Timeout: 30 * time.Second, }) if err != nil { log.Fatal(err) } defer client.Close() ``` **Python**: ```python client = BzzzClient( endpoint="http://localhost:8080", role="your_role", timeout=30.0 ) # Use async context manager for proper cleanup async with client: # Your code here pass ``` **JavaScript**: ```javascript const client = new BzzzClient({ endpoint: 'http://localhost:8080', role: 'your_role', timeout: 30000 }); // Proper cleanup process.on('SIGINT', async () => { await client.close(); process.exit(0); }); ``` **Rust**: ```rust let client = BzzzClient::new(Config { endpoint: "http://localhost:8080".to_string(), role: "your_role".to_string(), timeout: Duration::from_secs(30), ..Default::default() }).await?; ``` ### Error Handling Each language demonstrates proper error handling: - **Go**: Explicit error checking with wrapped errors - **Python**: Exception handling with custom exception types - **JavaScript**: Promise-based error handling with try/catch - **Rust**: Result types with proper error propagation ### Event Processing All examples show event streaming patterns: 1. **Subscribe** to event streams 2. **Process** events in async loops 3. **Handle** different event types appropriately 4. **Cleanup** subscriptions on shutdown ## Production Considerations ### Security - Never log private keys or sensitive content - Validate all inputs from external systems - Use secure credential storage (environment variables, secret management) - Implement proper access controls ### Performance - Use connection pooling for high-throughput applications - Implement backoff strategies for failed operations - Monitor resource usage and implement proper cleanup - Consider batching operations where appropriate ### Reliability - Implement proper error handling and retry logic - Use circuit breakers for external dependencies - Implement graceful shutdown procedures - Add comprehensive logging for debugging ### Monitoring - Track key performance metrics - Implement health checks - Monitor error rates and response times - Set up alerts for critical failures ## Troubleshooting ### Connection Issues ```bash # Check BZZZ node is running curl http://localhost:8080/api/agent/status # Verify network connectivity telnet localhost 8080 ``` ### Permission Errors - Verify your role has appropriate permissions - Check Age key configuration - Confirm role definitions in BZZZ configuration ### Performance Issues - Monitor network latency to BZZZ node - Check resource usage (CPU, memory) - Verify proper cleanup of connections - Consider connection pooling for high load ## Contributing To add new examples: 1. Create appropriate language directory structure 2. Include comprehensive documentation 3. Add error handling and cleanup 4. Test with different BZZZ configurations 5. Update this README with new examples ## Cross-References - **SDK Documentation**: [../docs/BZZZv2B-SDK.md](../docs/BZZZv2B-SDK.md) - **API Reference**: [../docs/API_REFERENCE.md](../docs/API_REFERENCE.md) - **User Manual**: [../docs/USER_MANUAL.md](../docs/USER_MANUAL.md) - **Developer Guide**: [../docs/DEVELOPER.md](../docs/DEVELOPER.md) --- **BZZZ SDK Examples v2.0** - Comprehensive examples demonstrating BZZZ integration across multiple programming languages with real-world patterns and best practices.