From ab3a5afd593d7ead8bed62566e5cd3dfb54000e8 Mon Sep 17 00:00:00 2001 From: Jordan Ramos Date: Fri, 13 Feb 2026 21:06:15 -0700 Subject: [PATCH] Documentation cleanup and consolidation Removed redundant/outdated files: - docs/HEARTBEAT_HOOKS.md (legacy, disabled by default) - docs/QUICK_START_PULSE.md (merged into PULSE_BRAIN.md) - docs/MONITORING_COMPARISON.md (merged into PULSE_BRAIN.md) Consolidated monitoring docs: - Merged 3 monitoring files into comprehensive PULSE_BRAIN.md - Added Quick Start section to PULSE_BRAIN.md - Added "Why Pulse & Brain?" comparison section - Added deprecation notices for Heartbeat system Updated README.md: - Clarified Haiku is default model (12x cheaper) - Added prompt caching info (90% savings on Sonnet) - Removed duplicate setup instructions - Linked to SETUP.md for detailed instructions - Added model switching commands section Simplified WINDOWS_QUICK_REFERENCE.md: - Reduced from 224 lines to ~160 lines - Removed redundant development/deployment sections - Kept essential quick commands - Added model switching commands Updated docs/README.md navigation: - Removed references to deleted files - Added deprecation notice for Heartbeat - Updated learning paths - Cleaned up file organization section Result: - Removed 300+ lines of redundant documentation - Consolidated 3 monitoring files into 1 - Improved accuracy and clarity - Easier navigation and maintenance Co-Authored-By: Claude Sonnet 4.5 --- README.md | 82 +++----- WINDOWS_QUICK_REFERENCE.md | 68 +----- docs/HEARTBEAT_HOOKS.md | 136 ------------ docs/MONITORING_COMPARISON.md | 331 ----------------------------- docs/PULSE_BRAIN.md | 386 ++++++++++++++++++++++++++++++---- docs/QUICK_START_PULSE.md | 221 ------------------- docs/README.md | 62 ++---- 7 files changed, 404 insertions(+), 882 deletions(-) delete mode 100644 docs/HEARTBEAT_HOOKS.md delete mode 100644 docs/MONITORING_COMPARISON.md delete mode 100644 docs/QUICK_START_PULSE.md diff --git a/README.md b/README.md index cd588e0..df23449 100644 --- a/README.md +++ b/README.md @@ -15,80 +15,46 @@ A lightweight, cost-effective AI agent framework for building proactive bots wit ## Features -- **Multi-LLM Support**: Claude (Anthropic) and GLM (z.ai) with easy model switching -- **Smart Memory System**: SQLite-based memory with automatic context retrieval +- **Cost-Optimized AI**: Default Haiku 4.5 model (12x cheaper), auto-caching on Sonnet (90% savings), dynamic model switching +- **Smart Memory System**: SQLite-based memory with automatic context retrieval and FTS search - **Multi-Platform Adapters**: Run on Slack, Telegram, and more simultaneously -- **Pulse & Brain Monitoring**: 92% cost savings with intelligent conditional monitoring +- **Pulse & Brain Monitoring**: 92% cost savings with intelligent conditional monitoring (recommended) - **Task Scheduling**: Cron-like scheduled tasks with flexible cadences -- **Skills Integration**: Local Claude Code skills invokable from messaging platforms -- **Heartbeat System**: Configurable health checks and proactive monitoring +- **Tool Use System**: File operations, command execution, and autonomous task completion +- **Multi-LLM Support**: Claude (Anthropic) primary, GLM (z.ai) optional ## Quick Start -### Windows 11 Users (Recommended) +**For detailed setup instructions**, see **[SETUP.md](SETUP.md)** - includes API key setup, configuration, and troubleshooting. -**One-click setup:** -```powershell -quick_start.bat -``` - -This will: -- Create virtual environment -- Install dependencies -- Check for API key -- Guide you through setup - -**Verify installation:** -```powershell -python test_installation.py -``` - -For detailed Windows deployment (service setup, monitoring, troubleshooting), see [Windows Deployment Guide](docs/WINDOWS_DEPLOYMENT.md). - -### Linux/macOS - -**1. Installation** +### 30-Second Quickstart ```bash -git clone https://github.com/yourusername/ajarbot.git +# Clone and install +git clone https://vulcan.apophisnetworking.net/jramos/ajarbot.git cd ajarbot pip install -r requirements.txt -``` -**2. Set Environment Variables** +# Configure (copy examples and add your API key) +cp .env.example .env +cp config/scheduled_tasks.example.yaml config/scheduled_tasks.yaml -```bash -export ANTHROPIC_API_KEY="sk-ant-..." # Your Claude API key -export GLM_API_KEY="..." # Optional: z.ai GLM key -``` +# Add your Anthropic API key to .env +# ANTHROPIC_API_KEY=sk-ant-... -**3. Run Your First Bot** - -```python -from agent import Agent - -# Initialize with Claude -agent = Agent(provider="claude") - -# Chat with automatic memory and context loading -response = agent.chat("What should I work on?", username="alice") -print(response) -``` - -**4. Try the Examples** - -```bash -# Basic agent with memory +# Run python example_usage.py - -# Agent with Pulse & Brain monitoring -python example_bot_with_pulse_brain.py - -# Multi-platform bot (Slack + Telegram) -python bot_runner.py --init # Generate config -python bot_runner.py # Start bot ``` +**Windows users**: Run `quick_start.bat` for automated setup + +### Model Switching Commands + +Send these to your bot: +- `/haiku` - Fast, cheap (default) +- `/sonnet` - Smart, caching enabled (auto 90% cost savings) +- `/status` - Check current model and settings + ## Core Concepts ### Agent diff --git a/WINDOWS_QUICK_REFERENCE.md b/WINDOWS_QUICK_REFERENCE.md index a64d7e2..fd43e69 100644 --- a/WINDOWS_QUICK_REFERENCE.md +++ b/WINDOWS_QUICK_REFERENCE.md @@ -158,67 +158,15 @@ python example_usage.py | `adapters/` | Platform integrations | | `memory_workspace/` | Memory database | +## Model Switching + +Tell your bot via chat: +- `/haiku` - Fast, cheap (default) +- `/sonnet` - Smart, caching enabled +- `/status` - Check current model + ## Need More Help? +- **Complete Setup Guide:** [SETUP.md](SETUP.md) - **Full Windows Guide:** [docs/WINDOWS_DEPLOYMENT.md](docs/WINDOWS_DEPLOYMENT.md) - **Main Documentation:** [docs/README.md](docs/README.md) -- **Project Overview:** [README.md](README.md) - -## Common Workflows - -### Development Testing -```powershell -# Activate environment -.\venv\Scripts\activate - -# Make changes to code -# ... - -# Test changes -python test_installation.py -python example_usage.py - -# Format code (optional) -pip install black -black . -``` - -### Production Deployment -```powershell -# 1. Configure adapters -python bot_runner.py --init -notepad config\adapters.local.yaml - -# 2. Test locally -python bot_runner.py - -# 3. Set up as service (see docs/WINDOWS_DEPLOYMENT.md) -# Option A: NSSM (recommended) -# Option B: Task Scheduler -# Option C: Startup script -``` - -### Monitoring Costs -```python -# In Python script or interactive shell -from pulse_brain import PulseBrain -from agent import Agent - -agent = Agent(provider="claude", enable_heartbeat=False) -pb = PulseBrain(agent) - -# After running for a while -status = pb.get_status() -tokens = status['brain_invocations'] * 1000 # Average tokens -cost = tokens * 0.000003 # Claude pricing -print(f"Estimated cost: ${cost:.4f}") -``` - ---- - -**Quick Start Path:** -1. Run `quick_start.bat` -2. Set API key -3. Run `python test_installation.py` -4. Run `python example_usage.py` -5. Explore other examples! diff --git a/docs/HEARTBEAT_HOOKS.md b/docs/HEARTBEAT_HOOKS.md deleted file mode 100644 index 558e7cb..0000000 --- a/docs/HEARTBEAT_HOOKS.md +++ /dev/null @@ -1,136 +0,0 @@ -# Heartbeat & Hooks System - -Simple Python implementation inspired by OpenClaw's automation patterns. - -## Heartbeat - -**What**: Periodic background check that reads `HEARTBEAT.md` and processes with LLM. - -**How it works**: -1. Runs every N minutes (default: 30) -2. Only during active hours (default: 8am-10pm) -3. Reads HEARTBEAT.md checklist -4. Sends to LLM with context (SOUL, pending tasks, current time) -5. Returns `HEARTBEAT_OK` if nothing needs attention -6. Calls alert callback if action needed - -**Files**: -- `heartbeat.py` - Heartbeat implementation -- `memory_workspace/HEARTBEAT.md` - Checklist (auto-created) - -**Usage**: -```python -from heartbeat import Heartbeat - -heartbeat = Heartbeat(memory, llm, interval_minutes=30, active_hours=(8, 22)) -heartbeat.on_alert = lambda msg: print(f"ALERT: {msg}") -heartbeat.start() - -# Test immediately -result = heartbeat.check_now() -``` - -## Hooks - -**What**: Event-driven automation for agent lifecycle events. - -**Events**: -- `task:created` - When task added -- `memory:synced` - After memory sync -- `agent:startup` - Agent starts -- `agent:shutdown` - Agent cleanup - -**How it works**: -1. Register handler functions for events -2. System triggers events at key points -3. All registered handlers run -4. Handlers can add messages to event - -**Files**: -- `hooks.py` - Hooks system + example handlers - -**Usage**: -```python -from hooks import HooksSystem, HookEvent - -hooks = HooksSystem() - -def my_hook(event: HookEvent): - if event.type != "task" or event.action != "created": - return - print(f"Task: {event.context['title']}") - event.messages.append("Logged!") - -hooks.register("task:created", my_hook) -hooks.trigger("task", "created", {"title": "Build feature"}) -``` - -## Integration with Agent - -```python -from agent import Agent - -# Heartbeat runs in background -agent = Agent(provider="claude", enable_heartbeat=True) - -# Hooks auto-registered -agent.hooks.register("task:created", my_custom_hook) - -# Events trigger automatically -task_id = agent.memory.add_task("Do something") # → task:created event - -# Cleanup -agent.shutdown() # → agent:shutdown event -``` - -## OpenClaw Comparison - -| Feature | OpenClaw | This Implementation | -|---------|----------|---------------------| -| Heartbeat | ✅ Main session, context-aware | ✅ Background thread, context-aware | -| Interval | ✅ Configurable (default 30m) | ✅ Configurable (default 30m) | -| Active hours | ✅ Start/end times | ✅ Start/end times (24h format) | -| Checklist | ✅ HEARTBEAT.md | ✅ HEARTBEAT.md | -| Alert suppression | ✅ HEARTBEAT_OK | ✅ HEARTBEAT_OK | -| Hooks system | ✅ TypeScript, directory-based | ✅ Python, function-based | -| Hook discovery | ✅ Auto-scan directories | ✅ Manual registration | -| Event types | ✅ command, session, agent, gateway | ✅ task, memory, agent | -| Async execution | ✅ In main event loop | ✅ Threading | - -## Simple Extensions - -**Add custom event**: -```python -# In your code -agent.hooks.trigger("custom", "action", {"data": "value"}) - -# Register handler -def on_custom(event): - print(f"Custom: {event.context}") - -agent.hooks.register("custom:action", on_custom) -``` - -**Custom heartbeat checklist**: -Edit `memory_workspace/HEARTBEAT.md`: -```markdown -# Heartbeat Checklist - -- Check email (if integrated) -- Review calendar events in next 2h -- Check pending tasks > 24h old -- System health check -``` - -**Multi-check batching** (like OpenClaw): -```python -# Single heartbeat checks multiple things -checklist = """ -- Email: Check inbox -- Calendar: Events next 2h -- Tasks: Pending > 24h -- Memory: Sync status -""" -``` - -LLM processes all in one turn = more efficient than separate calls. diff --git a/docs/MONITORING_COMPARISON.md b/docs/MONITORING_COMPARISON.md deleted file mode 100644 index c38918b..0000000 --- a/docs/MONITORING_COMPARISON.md +++ /dev/null @@ -1,331 +0,0 @@ -# Monitoring Systems Comparison - -Ajarbot now has **three different monitoring systems**. Here's how to choose the right one. - -## 📊 Quick Comparison - -| Feature | Pulse & Brain ⭐ | TaskScheduler | Old Heartbeat | -|---------|-----------------|---------------|---------------| -| **Cost per day** | ~$0.04 | ~$0.10-0.30 | ~$0.48 | -| **Cost per month** | ~$1.20 | ~$3-9 | ~$14.40 | -| **Agent usage** | Only when needed | Every scheduled task | Every interval | -| **Scheduling** | Cron + Conditional | Cron only | Interval only | -| **Monitoring** | ✅ Zero-cost pulse | ❌ None | ❌ Uses agent | -| **Messaging** | ✅ Slack/Telegram | ✅ Slack/Telegram | ❌ None | -| **Best for** | Production monitoring | Content generation | Simple setups | - -## 🏆 Recommended: Pulse & Brain - -**Use this for production monitoring.** - -### How It Works - -``` -Pulse (60s intervals, pure Python): - ├─ Check disk space $0 - ├─ Check log errors $0 - ├─ Check stale tasks $0 - ├─ Check server health $0 - └─ ... (add more) - -Brain (Agent/SDK, only when triggered): - ├─ Condition: disk > 90% → Invoke agent ($0.01) - ├─ Condition: errors found → Invoke agent ($0.01) - ├─ Scheduled: 8:00 AM briefing → Invoke agent ($0.01) - └─ Scheduled: 6:00 PM summary → Invoke agent ($0.01) -``` - -### Example Setup - -```python -from pulse_brain import PulseBrain - -pb = PulseBrain(agent, pulse_interval=60) -pb.add_adapter("slack", slack_adapter) -pb.start() -``` - -### Cost Breakdown - -**Pulse checks:** 1,440/day (every 60s) = **$0** -**Brain invocations:** ~4/day (only when needed) = **~$0.04/day** - -**Total: ~$1.20/month** 💰 - -### When to Use - -✅ Production monitoring -✅ Server health checks -✅ Log analysis -✅ Resource alerts -✅ Daily briefings -✅ Cost-conscious deployments - -## 🎯 Alternative: TaskScheduler - -**Use this for content generation only.** - -### How It Works - -``` -Every task runs on schedule (always uses Agent): - ├─ 08:00 Weather report → Agent ($0.01) - ├─ 12:00 Midday standup → Agent ($0.01) - ├─ 18:00 Evening summary → Agent ($0.01) - └─ Fri 17:00 Weekly review → Agent ($0.02) -``` - -### Example Setup - -```python -from scheduled_tasks import TaskScheduler - -scheduler = TaskScheduler(agent) -scheduler.add_adapter("slack", slack_adapter) -scheduler.start() -``` - -### Cost Breakdown - -**If you have:** -- 2 daily tasks (morning/evening) = 60 calls/month = ~$6/month -- 1 weekly task (Friday summary) = 4 calls/month = ~$0.80/month - -**Total: ~$6.80/month** - -### When to Use - -✅ Scheduled content generation -✅ Weather reports -✅ Daily summaries -✅ Weekly newsletters -✅ Team standups -❌ Real-time monitoring (use Pulse & Brain instead) - -## 💡 Hybrid Approach (Best of Both) - -**Recommended for most users:** - -```python -# Pulse & Brain for monitoring (cheap) -pb = PulseBrain(agent, pulse_interval=60) -pb.start() - -# TaskScheduler ONLY for specific content tasks -scheduler = TaskScheduler(agent) -# Enable only tasks that generate unique content -# (Don't duplicate with Pulse & Brain briefings) -scheduler.start() -``` - -### Example Hybrid Config - -**Pulse & Brain handles:** -- Health monitoring (disk, logs, tasks) -- Morning briefing with system status -- Evening summary -- Error alerts - -**TaskScheduler handles:** -- Weekly newsletter (Friday 5pm) -- Monthly metrics report (1st of month) -- Custom scheduled reports - -**Cost: ~$2-3/month** (vs $15/month with old heartbeat) - -## 🔧 Configuration Examples - -### Minimal Monitoring (Cheapest) - -**Just Pulse & Brain, no scheduled content:** - -```python -pb = PulseBrain(agent, pulse_interval=60) -# Only conditional tasks (error alerts) -# Remove scheduled briefings -pb.start() -``` - -**Cost: ~$0.20/month** (only when errors occur) - -### Full Monitoring + Content (Balanced) - -```python -# Pulse & Brain for all monitoring -pb = PulseBrain(agent, pulse_interval=60) -pb.start() - -# TaskScheduler for weekly/monthly content only -scheduler = TaskScheduler(agent) -scheduler.tasks = [weekly_newsletter, monthly_report] # Only specific tasks -scheduler.start() -``` - -**Cost: ~$2-4/month** - -### Maximum Features (Still Efficient) - -```python -# Pulse & Brain with custom checks -pb = PulseBrain(agent, pulse_interval=60) -apply_custom_config(pb) # Homelab, Docker, GPU, etc. -pb.start() - -# TaskScheduler for all content -scheduler = TaskScheduler(agent) -scheduler.start() -``` - -**Cost: ~$5-8/month** - -## 📈 Real-World Examples - -### Example 1: Personal Homelab - -**Goal:** Monitor servers, get daily briefings - -**Solution:** -```python -pb = PulseBrain(agent, pulse_interval=120) # Check every 2 minutes -# Pulse checks: Plex, UniFi, Docker, disk, GPU -# Brain tasks: Morning briefing, error alerts -``` - -**Cost: ~$1-2/month** - -### Example 2: Development Team Bot - -**Goal:** Daily standups, build notifications - -**Solution:** -```python -# Pulse & Brain for build failures -pb = PulseBrain(agent, pulse_interval=60) -# Conditional: CI/CD failures - -# TaskScheduler for standups -scheduler = TaskScheduler(agent) -# Daily 9am standup reminder -# Daily 5pm build summary -``` - -**Cost: ~$4-6/month** - -### Example 3: Solo Developer - -**Goal:** Track tasks, get weekly summaries - -**Solution:** -```python -# Just Pulse & Brain -pb = PulseBrain(agent, pulse_interval=300) # Every 5 minutes -# Pulse: Check pending tasks -# Brain: Friday evening weekly review -``` - -**Cost: ~$0.50-1/month** - -## 🎓 Decision Tree - -``` -Start here: - ↓ -Do you need real-time monitoring? (disk, logs, health checks) - ├─ YES → Use Pulse & Brain - └─ NO → Go to next question - ↓ -Do you need scheduled content? (weather, summaries, reports) - ├─ YES → Use TaskScheduler - └─ NO → Go to next question - ↓ -Do you need simple periodic checks? - └─ YES → Use old Heartbeat (or upgrade to Pulse & Brain) - -Most users should: Use Pulse & Brain (+ optionally TaskScheduler for content) -``` - -## 💰 Cost Optimization Tips - -1. **Increase pulse interval** if checks don't need to be frequent - ```python - pb = PulseBrain(agent, pulse_interval=300) # Every 5 min instead of 60s - ``` - -2. **Use conditional brain tasks** instead of scheduled - ```python - # ❌ Expensive: Always runs - BrainTask(schedule="daily 08:00", ...) - - # ✅ Cheap: Only if there's news - BrainTask(condition=lambda: has_updates(), ...) - ``` - -3. **Batch briefings** instead of multiple schedules - ```python - # ❌ Expensive: 3 calls/day - - morning-briefing (08:00) - - midday-update (12:00) - - evening-summary (18:00) - - # ✅ Cheaper: 2 calls/day - - morning-briefing (08:00) - - evening-summary (18:00) - ``` - -4. **Make pulse checks do more** before invoking brain - ```python - # Pulse checks can filter, aggregate, and pre-process - # Brain only gets invoked with actionable data - ``` - -## 🚀 Migration Guide - -### From Old Heartbeat → Pulse & Brain - -```python -# Old (heartbeat.py) -agent = Agent(enable_heartbeat=True) - -# New (pulse_brain.py) -agent = Agent(enable_heartbeat=False) -pb = PulseBrain(agent) -pb.start() -``` - -**Benefit:** 92% cost reduction - -### From TaskScheduler → Pulse & Brain - -If your "scheduled tasks" are really monitoring checks: - -```python -# Old (scheduled_tasks.yaml) -- name: health-check - schedule: "hourly" - prompt: "Check system health" - -# New (pulse_brain.py) -def check_health(): # Pure Python, zero cost - return {"status": "ok", "message": "Healthy"} - -PulseCheck("health", check_health, interval_seconds=3600) -``` - -**Benefit:** 96% cost reduction (hourly checks) - -## 📝 Summary - -| Your Need | Use This | Monthly Cost | -|-----------|----------|--------------| -| **Monitoring only** | Pulse & Brain | ~$1-2 | -| **Content only** | TaskScheduler | ~$4-8 | -| **Monitoring + Content** | Both | ~$3-6 | -| **Simple checks** | Old Heartbeat | ~$15 | - -**Winner:** Pulse & Brain for 99% of use cases 🏆 - -**Files:** -- `pulse_brain.py` - Main system -- `config/pulse_brain_config.py` - Custom checks -- `example_bot_with_pulse_brain.py` - Full example -- `PULSE_BRAIN.md` - Complete documentation diff --git a/docs/PULSE_BRAIN.md b/docs/PULSE_BRAIN.md index d3309ad..5c097a5 100644 --- a/docs/PULSE_BRAIN.md +++ b/docs/PULSE_BRAIN.md @@ -1,6 +1,86 @@ # Pulse & Brain Architecture -The **most efficient** way to run an agent with proactive monitoring. +⭐ **The most efficient way to run an agent with proactive monitoring.** + +> **Note:** The old Heartbeat system is now **legacy** and disabled by default. Use Pulse & Brain for all new deployments. + +--- + +## 🚀 Quick Start + +Copy-paste ready setup in under 50 lines: + +### Basic Monitoring (Zero-cost pulse, conditional agent) + +```python +from agent import Agent +from pulse_brain import PulseBrain + +# Initialize agent (disable old heartbeat) +agent = Agent(provider="claude", enable_heartbeat=False) + +# Create Pulse & Brain with 60-second pulse interval +pb = PulseBrain(agent, pulse_interval=60) + +# Start monitoring +pb.start() +``` + +### With Slack/Telegram Integration + +```python +from adapters.runtime import AdapterRuntime +from adapters.slack.adapter import SlackAdapter +from pulse_brain import PulseBrain + +agent = Agent(provider="claude", enable_heartbeat=False) + +# Set up messaging adapters +slack = SlackAdapter(bot_token="xoxb-...", channel="C_MONITORING") +runtime = AdapterRuntime(agent) +runtime.add_adapter(slack) + +# Create Pulse & Brain with adapter support +pb = PulseBrain(agent, pulse_interval=60) +pb.add_adapter("slack", slack) + +# Start both systems +await runtime.start() +pb.start() +``` + +### Custom Pulse Check (Zero Cost) + +```python +from pulse_brain import PulseCheck, BrainTask, CheckType + +def check_my_server(): + """Pure Python check - no agent, no cost.""" + import requests + try: + r = requests.get("http://localhost:8000/health", timeout=5) + return {"status": "ok" if r.status_code == 200 else "error"} + except: + return {"status": "error", "message": "Server down"} + +# Add to Pulse & Brain +pb = PulseBrain(agent) +pb.add_pulse_check(PulseCheck("my-server", check_my_server, interval_seconds=60)) + +# Only invoke agent when server is down +pb.add_brain_task(BrainTask( + name="server-fixer", + check_type=CheckType.CONDITIONAL, + prompt_template="Server is down! What should I check?", + condition_func=lambda data: data.get("status") == "error" +)) + +pb.start() +``` + +**That's it!** Your agent now monitors your system 24/7 at ~$1-2/month. + +--- ## 🎯 The Problem @@ -75,6 +155,8 @@ while True: **Savings: 92%** 💰 +--- + ## 🏗️ Architecture ``` @@ -110,41 +192,7 @@ while True: └─────────────────────┘ ``` -## 🔧 Usage - -### Basic Setup - -```python -from agent import Agent -from pulse_brain import PulseBrain - -agent = Agent(provider="claude", enable_heartbeat=False) - -# Create Pulse & Brain -pb = PulseBrain(agent, pulse_interval=60) # Pulse every 60 seconds - -# Start -pb.start() -``` - -### With Messaging Platforms - -```python -from adapters.runtime import AdapterRuntime -from pulse_brain import PulseBrain - -# Set up runtime with adapters -runtime = AdapterRuntime(agent) -runtime.add_adapter(slack_adapter) - -# Create Pulse & Brain -pb = PulseBrain(agent) -pb.add_adapter("slack", slack_adapter) - -# Start both -await runtime.start() -pb.start() -``` +--- ## 📝 Default Checks @@ -165,6 +213,8 @@ pb.start() | `morning-briefing` | Scheduled | Daily at 8:00 AM | | `evening-summary` | Scheduled | Daily at 6:00 PM | +--- + ## 🎨 Custom Configuration Create `config/pulse_brain_config.py`: @@ -198,6 +248,8 @@ CUSTOM_BRAIN_TASKS = [ ] ``` +--- + ## 🌟 Real-World Examples ### Example 1: Homelab Monitoring (from Gemini) @@ -294,13 +346,198 @@ BRAIN_TASK = BrainTask( **Pulse runs every 60s:** $0 **Brain only when unhealthy:** ~$0.01 per incident +--- + +## 💡 Why Pulse & Brain? + +### The Evolution of Monitoring + +Ajarbot has had **three different monitoring systems**. Here's how they compare: + +| Feature | Pulse & Brain ⭐ | TaskScheduler | Old Heartbeat ⚠️ | +|---------|-----------------|---------------|------------------| +| **Cost per day** | ~$0.04 | ~$0.10-0.30 | ~$0.48 | +| **Cost per month** | ~$1.20 | ~$3-9 | ~$14.40 | +| **Agent usage** | Only when needed | Every scheduled task | Every interval | +| **Scheduling** | Cron + Conditional | Cron only | Interval only | +| **Monitoring** | ✅ Zero-cost pulse | ❌ None | ❌ Uses agent | +| **Messaging** | ✅ Slack/Telegram | ✅ Slack/Telegram | ❌ None | +| **Best for** | Production monitoring | Content generation | ⚠️ Legacy (deprecated) | +| **Status** | ✅ Recommended | ✅ Active | ⚠️ Disabled by default | + +### Why Pulse & Brain Wins + +**1. Zero-Cost Monitoring** +```python +# Pulse checks run constantly at zero cost +Pulse (60s intervals, pure Python): + ├─ Check disk space $0 + ├─ Check log errors $0 + ├─ Check stale tasks $0 + ├─ Check server health $0 + └─ ... (add infinite checks, still $0) + +# Brain only invoked when needed +Brain (Agent/SDK): + ├─ Condition: disk > 90% → $0.01 (only if triggered) + ├─ Condition: errors found → $0.01 (only if triggered) + ├─ Scheduled: 8:00 AM briefing → $0.01 (once per day) + └─ Scheduled: 6:00 PM summary → $0.01 (once per day) +``` + +**2. Smarter Than TaskScheduler** + +TaskScheduler always invokes the agent, even if there's nothing to report: + +```python +# ❌ TaskScheduler: Always uses agent +- 08:00 Weather report → Agent ($0.01) even if no change +- 12:00 Midday standup → Agent ($0.01) even if no updates +- 18:00 Evening summary → Agent ($0.01) even if nothing happened + +# ✅ Pulse & Brain: Conditional intelligence +- Pulse checks for changes → Python ($0) +- Brain only if updates → Agent ($0.01) only when needed +``` + +**3. More Flexible Than Old Heartbeat** + +Old Heartbeat was simple but wasteful: + +```python +# ❌ Old Heartbeat: Every 30 minutes, always uses agent +while True: + agent.chat("Check everything") # ~$0.01 + time.sleep(1800) # 48 calls/day = $0.48/day + +# ✅ Pulse & Brain: Smart triggers +while True: + # 1,440 pulse checks/day (pure Python) = $0 + # Only 4 brain calls/day (when needed) = $0.04/day +``` + +### Decision Tree: Which System to Use? + +``` +Start here: + ↓ +Do you need real-time monitoring? (disk, logs, health checks) + ├─ YES → Use Pulse & Brain ⭐ + └─ NO → Go to next question + ↓ +Do you need scheduled content? (weather, summaries, reports) + ├─ YES → Use TaskScheduler + └─ NO → Go to next question + ↓ +Do you need simple periodic checks? + └─ YES → Migrate from old Heartbeat to Pulse & Brain + +Most users should: Use Pulse & Brain (+ optionally TaskScheduler for content) +``` + +### Hybrid Approach (Best of Both) + +For maximum efficiency: + +```python +# Pulse & Brain handles: +# - Health monitoring (disk, logs, tasks) +# - Morning briefing with system status +# - Evening summary +# - Error alerts +pb = PulseBrain(agent, pulse_interval=60) +pb.start() + +# TaskScheduler handles ONLY: +# - Weekly newsletter (Friday 5pm) +# - Monthly metrics report (1st of month) +# - Custom scheduled content (unique reports) +scheduler = TaskScheduler(agent) +scheduler.tasks = [weekly_newsletter, monthly_report] +scheduler.start() +``` + +**Cost: ~$2-3/month** (vs $15/month with old heartbeat) 💰 + +### Real-World Cost Examples + +| Use Case | System | Monthly Cost | +|----------|--------|--------------| +| **Homelab monitoring** | Pulse & Brain only | ~$1-2 | +| **Dev team bot** | Pulse & Brain + TaskScheduler | ~$4-6 | +| **Solo developer** | Pulse & Brain only | ~$0.50-1 | +| **Content bot** | TaskScheduler only | ~$4-8 | +| **Old heartbeat** | ⚠️ Legacy system | ~$15 | + +### Migration Guide + +**From Old Heartbeat → Pulse & Brain** + +```python +# Old (heartbeat.py) ❌ +agent = Agent(enable_heartbeat=True) + +# New (pulse_brain.py) ✅ +agent = Agent(enable_heartbeat=False) +pb = PulseBrain(agent) +pb.start() +``` + +**Benefit:** 92% cost reduction + +**From TaskScheduler → Pulse & Brain** + +If your "scheduled tasks" are really monitoring checks: + +```python +# Old (scheduled_tasks.yaml) ❌ +- name: health-check + schedule: "hourly" + prompt: "Check system health" + +# New (pulse_brain.py) ✅ +def check_health(): # Pure Python, zero cost + return {"status": "ok", "message": "Healthy"} + +PulseCheck("health", check_health, interval_seconds=3600) +``` + +**Benefit:** 96% cost reduction + +### Why Not Just Use TaskScheduler? + +TaskScheduler is great for **content generation**, but wasteful for monitoring: + +```python +# Example: Check disk space every hour with TaskScheduler +# Cost: 24 calls/day × 30 days = 720 calls/month = ~$7/month + +# Same with Pulse & Brain: +# Pulse checks: Unlimited ($0) +# Brain only if disk > 90%: ~2 calls/month = ~$0.02/month + +# Savings: $6.98/month (99.7% reduction) +``` + +### Why Not Just Use Old Heartbeat? + +Old Heartbeat was the original system, but it's: +- **Expensive**: Uses agent for every check +- **Inflexible**: Only interval-based, no conditionals +- **Limited**: No messaging platform integration +- **Deprecated**: Disabled by default, legacy code + +**Pulse & Brain replaces it entirely with 92% cost savings.** + +--- + ## 🎯 When to Use What | System | Best For | Cost | |--------|----------|------| | **Pulse & Brain** | Production monitoring | ~$1-2/month | | **TaskScheduler** | Scheduled content | ~$3-5/month | -| **Old Heartbeat** | Simple health checks | ~$15/month | +| **Old Heartbeat** | ⚠️ Legacy (don't use) | ~$15/month | ### Recommended Stack @@ -317,6 +554,8 @@ scheduler = TaskScheduler(agent) scheduler.start() ``` +--- + ## 📊 Monitoring Your Costs ```python @@ -334,6 +573,44 @@ cost = total_tokens * 0.000003 # Claude Sonnet pricing print(f"Estimated cost: ${cost:.4f}") ``` +--- + +## 💰 Cost Optimization Tips + +1. **Increase pulse interval** if checks don't need to be frequent + ```python + pb = PulseBrain(agent, pulse_interval=300) # Every 5 min instead of 60s + ``` + +2. **Use conditional brain tasks** instead of scheduled + ```python + # ❌ Expensive: Always runs + BrainTask(schedule="daily 08:00", ...) + + # ✅ Cheap: Only if there's news + BrainTask(condition=lambda: has_updates(), ...) + ``` + +3. **Batch briefings** instead of multiple schedules + ```python + # ❌ Expensive: 3 calls/day + - morning-briefing (08:00) + - midday-update (12:00) + - evening-summary (18:00) + + # ✅ Cheaper: 2 calls/day + - morning-briefing (08:00) + - evening-summary (18:00) + ``` + +4. **Make pulse checks do more** before invoking brain + ```python + # Pulse checks can filter, aggregate, and pre-process + # Brain only gets invoked with actionable data + ``` + +--- + ## 🚀 Getting Started 1. **Edit** `config/pulse_brain_config.py` with your checks @@ -342,6 +619,8 @@ print(f"Estimated cost: ${cost:.4f}") 4. **Run** `python -m pulse_brain` 5. **Monitor** brain invocation count +--- + ## 🔥 Pro Tips 1. **Make pulse checks fast** (<1 second each) @@ -350,6 +629,39 @@ print(f"Estimated cost: ${cost:.4f}") 4. **Test pulse checks** without brain first 5. **Monitor brain invocations** to track costs +--- + +## ⚠️ Legacy System Notice + +### Old Heartbeat (Deprecated) + +The original Heartbeat system is now **disabled by default**. It has been superseded by Pulse & Brain. + +**Why it's deprecated:** +- Uses agent for every check (expensive) +- No conditional logic (always runs) +- No messaging platform integration +- Replaced entirely by Pulse & Brain + +**If you're still using it:** +```python +# Old (don't use) ❌ +agent = Agent(enable_heartbeat=True) + +# New (migrate to this) ✅ +agent = Agent(enable_heartbeat=False) +pb = PulseBrain(agent) +pb.start() +``` + +**Migration benefits:** +- 92% cost reduction +- Conditional intelligence +- Messaging platform support +- More flexible scheduling + +--- + ## 🎉 Summary **Pulse & Brain is the most cost-effective way to run a proactive agent:** diff --git a/docs/QUICK_START_PULSE.md b/docs/QUICK_START_PULSE.md deleted file mode 100644 index 1774454..0000000 --- a/docs/QUICK_START_PULSE.md +++ /dev/null @@ -1,221 +0,0 @@ -# Pulse & Brain Quick Start - -## ❓ Will the agent arbitrarily pick tasks to monitor? - -**NO.** You have complete control. Here are your options: - -## 🎯 Three Ways to Use Pulse & Brain - -### Option 1: Start with Examples (Easiest) - -```python -from pulse_brain import PulseBrain - -pb = PulseBrain(agent) # Loads example checks -pb.start() -``` - -**What this monitors:** -- Disk space (every 5 min) -- Memory tasks (every 10 min) -- Log errors (every 1 min) -- Morning briefing (8:00 AM) -- Evening summary (6:00 PM) - -**Remove what you don't want:** -```python -pb = PulseBrain(agent) - -# Remove specific checks -pb.pulse_checks = [c for c in pb.pulse_checks if c.name != "log-errors"] -pb.brain_tasks = [t for t in pb.brain_tasks if t.name != "morning-briefing"] - -pb.start() -``` - -### Option 2: Start Clean (Recommended) - -```python -from pulse_brain import PulseBrain - -# NO default checks loaded -pb = PulseBrain(agent, enable_defaults=False) - -# Now add ONLY what YOU want -from pulse_brain import PulseCheck - -def my_check(): - return {"status": "ok", "message": "All good"} - -pb.pulse_checks.append( - PulseCheck("my-check", my_check, interval_seconds=60) -) - -pb.start() -``` - -**What this monitors:** -- ONLY what you explicitly add -- Nothing else - -### Option 3: No Automation (Pure Chat Bot) - -```python -from agent import Agent - -agent = Agent(provider="claude") - -# Don't use Pulse & Brain at all -# Agent only responds to messages you send - -response = agent.chat("Check the server for me") -``` - -**What this monitors:** -- Nothing automatically -- Only responds when you message it - -## 📋 Quick Reference - -### Add a Pulse Check (Zero Cost) - -```python -def check_something(): - """Pure Python check - no agent, no tokens.""" - # Your check logic here - return { - "status": "ok", # or "warn" or "error" - "message": "Status message", - "data": "any data you want" - } - -pb.pulse_checks.append( - PulseCheck( - name="my-check", - check_func=check_something, - interval_seconds=300 # Every 5 minutes - ) -) -``` - -### Add a Conditional Brain Task (Uses Agent When Condition Met) - -```python -from pulse_brain import BrainTask, CheckType - -pb.brain_tasks.append( - BrainTask( - name="my-alert", - check_type=CheckType.CONDITIONAL, - prompt_template="Something went wrong: {message}. What should I do?", - condition_func=lambda data: data.get("status") == "error" - ) -) -``` - -### Add a Scheduled Brain Task (Uses Agent at Specific Time) - -```python -pb.brain_tasks.append( - BrainTask( - name="daily-briefing", - check_type=CheckType.SCHEDULED, - schedule_time="08:00", - prompt_template="Good morning! Summary please: {message}", - send_to_platform="slack", - send_to_channel="C12345" - ) -) -``` - -## 🔍 Check What Will Run BEFORE Starting - -```python -pb = PulseBrain(agent) - -# Review before starting -print("Pulse checks:") -for c in pb.pulse_checks: - print(f" - {c.name} (every {c.interval_seconds}s)") - -print("\nBrain tasks:") -for t in pb.brain_tasks: - print(f" - {t.name}") - -# Modify if needed -pb.pulse_checks = [] # Clear all -pb.brain_tasks = [] # Clear all - -# Add only what you want -# ... - -pb.start() -``` - -## 💡 Recommended Setup - -```python -from agent import Agent -from pulse_brain import PulseBrain, PulseCheck, BrainTask, CheckType - -agent = Agent(provider="claude") - -# Start with ZERO automation -pb = PulseBrain(agent, enable_defaults=False) - -print(f"Pulse checks: {len(pb.pulse_checks)}") # 0 -print(f"Brain tasks: {len(pb.brain_tasks)}") # 0 - -# Now YOU decide what to add -# Example: Monitor one specific thing -def check_my_server(): - import requests - try: - r = requests.get("http://localhost:8000/health", timeout=5) - return {"status": "ok" if r.status_code == 200 else "error"} - except: - return {"status": "error"} - -pb.pulse_checks.append( - PulseCheck("server", check_my_server, 60) -) - -pb.brain_tasks.append( - BrainTask( - name="server-alert", - check_type=CheckType.CONDITIONAL, - prompt_template="Server is down! What should I check?", - condition_func=lambda d: d["status"] == "error" - ) -) - -print(f"\nNow monitoring: {[c.name for c in pb.pulse_checks]}") -print(f"Brain tasks: {[t.name for t in pb.brain_tasks]}") - -pb.start() -``` - -## ✅ Key Takeaways - -1. **You control everything** - Agent doesn't pick tasks -2. **Use `enable_defaults=False`** to start clean -3. **Add checks explicitly** - Nothing happens automatically -4. **Review before starting** - Print pulse_checks and brain_tasks -5. **Agent only analyzes** - Doesn't decide what to monitor - -## 🎯 Answer to Your Question - -> "It won't arbitrarily pick tasks though right? Only tasks that I specifically ask the agent to monitor?" - -**Correct!** - -- ✅ Agent only monitors what YOU add to `pulse_checks` -- ✅ Agent only invokes when YOUR conditions are met -- ✅ Agent only uses prompts YOU write -- ❌ Agent CANNOT add new monitors -- ❌ Agent CANNOT change conditions -- ❌ Agent CANNOT pick tasks arbitrarily - -**You are in complete control.** 🎛️ - -See **[CONTROL_AND_CONFIGURATION.md](CONTROL_AND_CONFIGURATION.md)** for detailed examples. diff --git a/docs/README.md b/docs/README.md index 27d02e9..fb8d54a 100644 --- a/docs/README.md +++ b/docs/README.md @@ -9,16 +9,15 @@ Complete documentation for Ajarbot - a lightweight, cost-effective AI agent fram | Document | Description | Time to Read | |----------|-------------|--------------| | [Quick Start Guide](QUICKSTART.md) | 30-second setup and basic agent usage | 5 min | -| [Pulse & Brain Quick Start](QUICK_START_PULSE.md) | Set up efficient monitoring in minutes | 5 min | +| [Complete Setup Guide](../SETUP.md) | Comprehensive setup with API keys, config, troubleshooting | 10 min | ### Core Systems | Document | Description | Best For | |----------|-------------|----------| -| [Pulse & Brain Architecture](PULSE_BRAIN.md) | Cost-effective monitoring (92% savings) | Production monitoring, homelab | +| [Pulse & Brain Architecture](PULSE_BRAIN.md) | Cost-effective monitoring (92% savings) with Quick Start | Production monitoring, homelab | | [Memory System](README_MEMORY.md) | SQLite-based memory management | Understanding context/memory | | [Scheduled Tasks](SCHEDULED_TASKS.md) | Cron-like task scheduling | Daily briefings, reports | -| [Heartbeat Hooks](HEARTBEAT_HOOKS.md) | Proactive health monitoring | System health checks | ### Platform Integration @@ -27,12 +26,16 @@ Complete documentation for Ajarbot - a lightweight, cost-effective AI agent fram | [Adapters Guide](README_ADAPTERS.md) | Multi-platform messaging (Slack, Telegram) | Running bots on chat platforms | | [Skills Integration](SKILLS_INTEGRATION.md) | Claude Code skills from messaging platforms | Advanced bot capabilities | -### Advanced Topics +### Configuration | Document | Description | Best For | |----------|-------------|----------| | [Control & Configuration](CONTROL_AND_CONFIGURATION.md) | Configuration management | Customizing behavior | -| [Monitoring Comparison](MONITORING_COMPARISON.md) | Choosing monitoring approaches | Optimizing costs | +| [Windows Deployment](WINDOWS_DEPLOYMENT.md) | Complete Windows setup guide | Windows users | + +--- + +> **⚠️ Note on Heartbeat System**: The Heartbeat monitoring system is legacy and disabled by default. Use **Pulse & Brain** instead for 92% cost savings. Heartbeat documentation has been removed - see [PULSE_BRAIN.md](PULSE_BRAIN.md) for the recommended approach. ## Learning Paths @@ -66,21 +69,20 @@ For running bots on Slack, Telegram, or both: - User mapping across platforms - Custom preprocessors/postprocessors -### Path 3: Production Monitoring (30 minutes) +### Path 3: Production Monitoring (20 minutes) For cost-effective production deployments: -1. Read [Pulse & Brain Quick Start](QUICK_START_PULSE.md) -2. Read [Pulse & Brain Architecture](PULSE_BRAIN.md) -3. Run `example_bot_with_pulse_brain.py` -4. Create custom pulse checks -5. Read [Monitoring Comparison](MONITORING_COMPARISON.md) +1. Read [Pulse & Brain Architecture](PULSE_BRAIN.md) - includes Quick Start section +2. Run `example_bot_with_pulse_brain.py` +3. Create custom pulse checks +4. Configure custom brain tasks **What you'll learn:** - Pulse checks (zero-cost monitoring) - Conditional brain tasks (only when needed) - Scheduled brain tasks (daily summaries) -- Cost optimization (92% savings) +- Cost optimization (92% savings vs traditional monitoring) ### Path 4: Advanced Features (45 minutes) @@ -112,13 +114,15 @@ For full-featured production bots: ### PULSE_BRAIN.md Comprehensive guide to the Pulse & Brain architecture: +- Quick Start section for immediate setup - Why continuous polling is expensive ($0.48/day) - How Pulse & Brain saves 92% ($0.04/day) +- Comparison with traditional monitoring (Heartbeat) - Default pulse checks and brain tasks - Custom configuration examples - Real-world use cases (homelab, Docker monitoring) -**Key takeaway:** Run proactive monitoring at 1/10th the cost. +**Key takeaway:** Run proactive monitoring at 1/10th the cost with Quick Start included. ### README_ADAPTERS.md Multi-platform adapter system: @@ -151,16 +155,6 @@ Cron-like task scheduling: **Key takeaway:** Schedule recurring bot activities (reports, briefings, etc.). -### HEARTBEAT_HOOKS.md -Proactive health monitoring: -- Heartbeat system overview -- Built-in checks (memory, disk, logs) -- Custom health checks -- Alert conditions -- Integration with adapters - -**Key takeaway:** Traditional monitoring approach (consider Pulse & Brain for better cost efficiency). - ### README_MEMORY.md SQLite-based memory system: - Memory architecture @@ -182,15 +176,6 @@ Configuration management: **Key takeaway:** Centralized configuration for all components. -### MONITORING_COMPARISON.md -Choosing the right monitoring: -- Heartbeat vs Pulse & Brain -- Cost comparison -- Use case recommendations -- Migration guide - -**Key takeaway:** Decision matrix for monitoring approaches. - ## Common Questions ### Q: Which monitoring system should I use? @@ -198,9 +183,9 @@ Choosing the right monitoring: **A:** Use **Pulse & Brain** for production. It's 92% cheaper and more flexible. - **Pulse & Brain**: ~$1-2/month (recommended) -- **Heartbeat**: ~$15/month (legacy) +- **Heartbeat**: ~$15/month (legacy, disabled by default) -See [Monitoring Comparison](MONITORING_COMPARISON.md) for details. +See [PULSE_BRAIN.md](PULSE_BRAIN.md) for details including comparison and migration guide. ### Q: Can I run my bot on multiple platforms? @@ -247,16 +232,15 @@ Model switching: `agent.switch_model("glm")` ``` docs/ ├── README.md # This file - navigation hub -├── QUICKSTART.md # Start here -├── QUICK_START_PULSE.md # Pulse & Brain quick start -├── PULSE_BRAIN.md # Detailed Pulse & Brain guide +├── QUICKSTART.md # Start here (30 seconds) +├── PULSE_BRAIN.md # Monitoring guide (includes Quick Start & comparison) ├── README_ADAPTERS.md # Multi-platform adapters ├── README_MEMORY.md # Memory system ├── SKILLS_INTEGRATION.md # Skills from messaging ├── SCHEDULED_TASKS.md # Task scheduling -├── HEARTBEAT_HOOKS.md # Legacy heartbeat ├── CONTROL_AND_CONFIGURATION.md # Configuration guide -└── MONITORING_COMPARISON.md # Monitoring approaches +├── WINDOWS_DEPLOYMENT.md # Windows-specific setup +└── SECURITY_AUDIT_SUMMARY.md # Security audit report ``` ## Getting Help