Files
ajarbot/docs/WINDOWS_DEPLOYMENT.md

599 lines
11 KiB
Markdown
Raw Normal View History

# Windows 11 Deployment Guide
Complete guide for deploying and testing Ajarbot on Windows 11.
## Prerequisites
### 1. Install Python
Download and install Python 3.8 or higher from [python.org](https://www.python.org/downloads/):
```powershell
# Verify installation
python --version
# Should show: Python 3.8+
# Verify pip
pip --version
```
**Important:** During installation, check "Add Python to PATH"
### 2. Get API Keys
You'll need at least one of these:
**Claude (Anthropic)** - Recommended
1. Go to https://console.anthropic.com/
2. Create account or sign in
3. Navigate to API Keys
4. Create new key
5. Copy the key (starts with `sk-ant-`)
**GLM (z.ai)** - Optional
1. Go to https://z.ai
2. Sign up and get API key
## Quick Start (5 Minutes)
### 1. Clone or Navigate to Project
```powershell
# If you haven't already
cd c:\Users\fam1n\projects\ajarbot
```
### 2. Create Virtual Environment (Recommended)
```powershell
# Create virtual environment
python -m venv venv
# Activate it
.\venv\Scripts\activate
# You should see (venv) in your prompt
```
### 3. Install Dependencies
```powershell
pip install -r requirements.txt
```
Expected output:
```
Successfully installed anthropic-0.40.0 requests-2.31.0 watchdog-3.0.0 ...
```
### 4. Set Environment Variables
**Option A: PowerShell (temporary - current session only)**
```powershell
$env:ANTHROPIC_API_KEY = "sk-ant-your-key-here"
# Optional: GLM
$env:GLM_API_KEY = "your-glm-key-here"
```
**Option B: System Environment Variables (persistent)**
1. Press `Win + X` → System
2. Click "Advanced system settings"
3. Click "Environment Variables"
4. Under "User variables", click "New"
5. Variable name: `ANTHROPIC_API_KEY`
6. Variable value: `sk-ant-your-key-here`
7. Click OK
**Option C: .env file (recommended for development)**
```powershell
# Create .env file in project root
notepad .env
```
Add to `.env`:
```
ANTHROPIC_API_KEY=sk-ant-your-key-here
GLM_API_KEY=your-glm-key-here
```
Then install python-dotenv and load it:
```powershell
pip install python-dotenv
```
### 5. Test Basic Agent
```powershell
python example_usage.py
```
Expected output:
```
============================================================
Basic Agent Usage Example
============================================================
[Setup] Initializing agent with Claude...
[Setup] Agent initialized
[Test 1] Basic chat...
Agent: [Response from Claude]
[Test 2] Memory operations...
...
```
## Running Different Examples
### Basic Agent with Memory
```powershell
python example_usage.py
```
**What it does:**
- Creates agent with Claude
- Tests basic chat
- Demonstrates memory operations
- Shows task management
### Pulse & Brain Monitoring
```powershell
python example_bot_with_pulse_brain.py
```
**What it does:**
- Runs cost-effective monitoring
- Pure Python checks (zero cost)
- Conditional AI calls (only when needed)
- Shows real-time status
Press `Ctrl+C` to stop
### Task Scheduler
```powershell
python example_bot_with_scheduler.py
```
**What it does:**
- Schedules recurring tasks
- Demonstrates cron-like syntax
- Shows task execution
- Runs in background
Press `Ctrl+C` to stop
### Skills Integration
```powershell
python example_bot_with_skills.py
```
**What it does:**
- Loads Claude Code skills
- Allows skill invocation
- Demonstrates preprocessing
- Shows available skills
### Multi-Platform Bot (Slack + Telegram)
First, generate configuration:
```powershell
python bot_runner.py --init
```
This creates `config\adapters.local.yaml`
Edit the file:
```powershell
notepad config\adapters.local.yaml
```
Add your credentials:
```yaml
adapters:
slack:
enabled: true
credentials:
bot_token: "xoxb-your-token"
app_token: "xapp-your-token"
telegram:
enabled: true
credentials:
bot_token: "your-bot-token"
```
Run the bot:
```powershell
python bot_runner.py
```
## Testing Components
### Test Skills System
```powershell
python test_skills.py
```
Verifies:
- Skill discovery
- Skill loading
- Preprocessor functionality
### Test Scheduler
```powershell
python test_scheduler.py
```
Verifies:
- Task scheduling
- Schedule parsing
- Task execution
## Running as Windows Service (Production)
### Option 1: NSSM (Non-Sucking Service Manager)
**Install NSSM:**
1. Download from https://nssm.cc/download
2. Extract to `C:\nssm`
3. Add to PATH or use full path
**Create Service:**
```powershell
# Run as Administrator
nssm install Ajarbot "C:\Users\fam1n\projects\ajarbot\venv\Scripts\python.exe"
# Set parameters
nssm set Ajarbot AppParameters "bot_runner.py"
nssm set Ajarbot AppDirectory "C:\Users\fam1n\projects\ajarbot"
# Set environment variables
nssm set Ajarbot AppEnvironmentExtra ANTHROPIC_API_KEY=sk-ant-your-key
# Start service
nssm start Ajarbot
```
**Manage Service:**
```powershell
# Check status
nssm status Ajarbot
# Stop service
nssm stop Ajarbot
# Remove service
nssm remove Ajarbot confirm
```
### Option 2: Task Scheduler (Simpler)
**Create scheduled task:**
1. Open Task Scheduler (`Win + R``taskschd.msc`)
2. Create Basic Task
3. Name: "Ajarbot"
4. Trigger: "When computer starts"
5. Action: "Start a program"
6. Program: `C:\Users\fam1n\projects\ajarbot\venv\Scripts\python.exe`
7. Arguments: `bot_runner.py`
8. Start in: `C:\Users\fam1n\projects\ajarbot`
9. Finish
**Configure task:**
- Right-click task → Properties
- Check "Run whether user is logged on or not"
- Check "Run with highest privileges"
- Triggers tab → Edit → Check "Enabled"
### Option 3: Simple Startup Script
Create `start_ajarbot.bat`:
```batch
@echo off
cd /d C:\Users\fam1n\projects\ajarbot
call venv\Scripts\activate
set ANTHROPIC_API_KEY=sk-ant-your-key-here
python bot_runner.py
pause
```
Add to startup:
1. Press `Win + R`
2. Type `shell:startup`
3. Copy `start_ajarbot.bat` to the folder
## Running in Background
### Using PowerShell
```powershell
# Start in background
Start-Process python -ArgumentList "bot_runner.py" -WindowStyle Hidden -WorkingDirectory "C:\Users\fam1n\projects\ajarbot"
# Find process
Get-Process python | Where-Object {$_.CommandLine -like "*bot_runner*"}
# Stop process (get PID first)
Stop-Process -Id <PID>
```
### Using pythonw (No console window)
```powershell
# Run without console window
pythonw bot_runner.py
```
## Monitoring and Logs
### View Logs
By default, Python prints to console. To save logs:
**Option 1: Redirect to file**
```powershell
python bot_runner.py > logs\bot.log 2>&1
```
**Option 2: Add logging to code**
Create `config\logging_config.py`:
```python
import logging
from pathlib import Path
log_dir = Path("logs")
log_dir.mkdir(exist_ok=True)
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler(log_dir / "ajarbot.log"),
logging.StreamHandler()
]
)
```
Then in your scripts:
```python
import logging
logger = logging.getLogger(__name__)
logger.info("Bot started")
```
### Monitor Process
**Task Manager:**
1. Press `Ctrl + Shift + Esc`
2. Details tab
3. Find `python.exe`
4. Check CPU/Memory usage
**PowerShell:**
```powershell
# Monitor in real-time
while ($true) {
Get-Process python | Select-Object CPU, PM, StartTime
Start-Sleep 5
}
```
## Troubleshooting
### "Python is not recognized"
**Fix:**
1. Find Python installation: `C:\Users\fam1n\AppData\Local\Programs\Python\Python3XX`
2. Add to PATH:
- Win + X → System → Advanced → Environment Variables
- Edit PATH, add Python directory
- Add Scripts directory too
### "Module not found" errors
```powershell
# Ensure virtual environment is activated
.\venv\Scripts\activate
# Reinstall dependencies
pip install -r requirements.txt --force-reinstall
```
### "API key not found"
Verify environment variable:
```powershell
# Check if set
$env:ANTHROPIC_API_KEY
# Should show your key, not empty
```
If empty, set it again:
```powershell
$env:ANTHROPIC_API_KEY = "sk-ant-your-key"
```
### Port already in use (for adapters)
If running multiple instances:
```powershell
# Find process using port
netstat -ano | findstr :PORT_NUMBER
# Kill process
taskkill /PID <PID> /F
```
### Memory workspace errors
```powershell
# Delete and recreate
Remove-Item -Recurse -Force memory_workspace
python example_usage.py
```
### Firewall blocking (for Slack/Telegram)
1. Windows Security → Firewall & network protection
2. Allow an app through firewall
3. Add Python
4. Check both Private and Public
## Performance Tips
### 1. Use SSD for memory_workspace
If you have multiple drives, store memory on SSD:
```python
# In agent.py, modify workspace_path
workspace_path = "D:\fast_storage\ajarbot_memory"
```
### 2. Optimize Pulse Interval
For lower CPU usage:
```python
pb = PulseBrain(agent, pulse_interval=300) # 5 minutes instead of 60 seconds
```
### 3. Limit Memory Database Size
```python
# In memory_system.py, add retention policy
memory.cleanup_old_entries(days=30)
```
### 4. Run with pythonw
```powershell
# Lower priority, no console
pythonw bot_runner.py
```
## Security Considerations
### 1. Protect API Keys
Never commit `.env` or `adapters.local.yaml`:
```powershell
# Check .gitignore includes:
echo ".env" >> .gitignore
echo "config/*.local.yaml" >> .gitignore
```
### 2. Use Windows Credential Manager
Store API keys securely:
```python
import keyring
# Store key
keyring.set_password("ajarbot", "anthropic_key", "sk-ant-...")
# Retrieve key
api_key = keyring.get_password("ajarbot", "anthropic_key")
```
Install keyring:
```powershell
pip install keyring
```
### 3. Run with Limited User
Create dedicated user account:
1. Settings → Accounts → Family & other users
2. Add account → "Ajarbot Service"
3. Run service as this user (limited permissions)
## Development Workflow
### 1. Development Mode
```powershell
# Activate venv
.\venv\Scripts\activate
# Run with auto-reload (install watchdog)
pip install watchdog[watchmedo]
# Monitor and restart on changes
watchmedo auto-restart --directory=. --pattern=*.py --recursive -- python bot_runner.py
```
### 2. Testing Changes
```powershell
# Quick syntax check
python -m py_compile agent.py
# Run tests
python test_skills.py
python test_scheduler.py
```
### 3. Code Formatting
```powershell
# Install black
pip install black
# Format code
black .
```
## Next Steps
1. **Test locally:** Run `example_usage.py` to verify setup
2. **Configure adapters:** Set up Slack or Telegram
3. **Customize:** Edit pulse checks, schedules, or skills
4. **Deploy:** Choose service option (NSSM, Task Scheduler, or Startup)
5. **Monitor:** Check logs and system resources
## Quick Reference
### Start Bot
```powershell
.\venv\Scripts\activate
python bot_runner.py
```
### Stop Bot
```
Ctrl + C
```
### View Logs
```powershell
type logs\bot.log
```
### Check Status
```powershell
python bot_runner.py --health
```
### Update Dependencies
```powershell
pip install -r requirements.txt --upgrade
```
---
**Need Help?**
- Check [main documentation](README.md)
- Review [troubleshooting](#troubleshooting) section
- Check Windows Event Viewer for service errors
- Run examples to isolate issues