Setting up OpenClaw
OpenClaw is the most powerful framework for building AI agents that actually work in production. In this guide, you'll go from zero to running your first intelligent agent in under an hour.
What You'll Build
By the end of this tutorial, you'll have: - ā OpenClaw installed and configured - ā A simple agent that monitors your email - ā Understanding of how to extend it for your needs
Prerequisites
Before we start, make sure you have: - macOS (OpenClaw currently supports Mac only) - Node.js 18+ installed - Basic terminal knowledge - API keys for Claude (we'll help you get these)
Step 1: Installation
Download and Install
```bash
Download the latest OpenClaw release
curl -L https://github.com/openclaw/openclaw/releases/latest/download/openclaw-macos.zip -o openclaw.zipExtract and install
unzip openclaw.zip sudo mv openclaw /usr/local/bin/ ```Verify Installation
```bash openclaw --version ```
You should see something like `openclaw v1.2.0`.
Step 2: Initial Configuration
Create Your Workspace
```bash
Create a dedicated directory for your agents
mkdir ~/my-agents cd ~/my-agentsInitialize your first agent workspace
openclaw init email-monitor cd email-monitor ```This creates a structured directory with: - `agents/` - Your agent configurations - `skills/` - Custom capabilities - `memory/` - Agent knowledge and history - `config/` - System settings
Get Your API Keys
OpenClaw works best with Anthropic's Claude:
1. Visit console.anthropic.com 2. Sign up for an account 3. Generate an API key 4. Copy the key (starts with `sk-ant-`)
Configure Your Agent
```bash
Set up your API key securely
openclaw config set anthropic.api_keyWhen prompted, paste your API key
```Step 3: Create Your First Agent
Define the Agent
Create `agents/email-monitor.yaml`:
```yaml name: email-monitor description: "Monitors email and alerts on important messages" model: claude-3-sonnet
personality: | You are a professional assistant who helps manage email efficiently. You're proactive, concise, and focused on actionable insights.
goals: - Monitor incoming emails for urgent or important messages - Categorize emails by priority and type - Provide clear summaries and recommended actions
skills: - email-reader - priority-classifier - notification-sender
memory: enabled: true retention_days: 30
triggers: - type: schedule interval: "/15 *" # Every 15 minutes action: check_new_emails ```
Create Email Reading Skill
Create `skills/email-reader.py`:
```python import imaplib import email from datetime import datetime, timedelta from openclaw import skill, config
@skill def check_new_emails(): """Check for new emails and return unread messages""" # Email configuration (you'll add your credentials) IMAP_SERVER = config.get('email.imap_server', 'imap.gmail.com') EMAIL = config.get('email.address') PASSWORD = config.get('email.password') # Use app password for Gmail if not EMAIL or not PASSWORD: return {"error": "Email credentials not configured"} try: # Connect to email server mail = imaplib.IMAP4_SSL(IMAP_SERVER) mail.login(EMAIL, PASSWORD) mail.select('inbox') # Search for unread emails from last hour since = (datetime.now() - timedelta(hours=1)).strftime("%d-%b-%Y") _, message_ids = mail.search(None, f'(UNSEEN SINCE "{since}")') emails = [] for msg_id in message_ids[0].split(): _, msg_data = mail.fetch(msg_id, '(RFC822)') email_body = msg_data[0][1] email_message = email.message_from_bytes(email_body) emails.append({ 'id': msg_id.decode(), 'subject': email_message['subject'], 'from': email_message['from'], 'date': email_message['date'], 'snippet': get_email_snippet(email_message) }) mail.logout() return {"emails": emails, "count": len(emails)} except Exception as e: return {"error": str(e)}
def get_email_snippet(email_message): """Extract first 200 characters of email body""" body = "" if email_message.is_multipart(): for part in email_message.walk(): if part.get_content_type() == "text/plain": body = part.get_payload(decode=True).decode() break else: body = email_message.get_payload(decode=True).decode() return body[:200] + "..." if len(body) > 200 else body ```
Configure Email Access
```bash
Set your email credentials
openclaw config set email.address [email protected] openclaw config set email.imap_server imap.gmail.com openclaw config set email.password your-app-password ```Step 4: Add Intelligence
Create Priority Classification
Create `skills/priority-classifier.py`:
```python from openclaw import skill, ai
@skill def classify_email_priority(emails): """Classify emails by priority using AI""" if not emails: return {"classifications": []} prompt = f""" Analyze these emails and classify each by priority (HIGH, MEDIUM, LOW) and type (URGENT, BUSINESS, PERSONAL, SPAM). Consider HIGH priority: - Messages from known contacts about urgent matters - Work-related deadlines or emergencies - Important personal matters Emails to analyze: {format_emails_for_analysis(emails)} Return a JSON array with: [{{ "id": "email_id", "priority": "HIGH|MEDIUM|LOW", "type": "URGENT|BUSINESS|PERSONAL|SPAM", "reason": "brief explanation" }}] """ response = ai.complete(prompt, model="claude-3-sonnet") return {"classifications": response.json()}
def format_emails_for_analysis(emails): """Format emails for AI analysis""" formatted = [] for email in emails: formatted.append(f""" ID: {email['id']} From: {email['from']} Subject: {email['subject']} Snippet: {email['snippet']} """) return "\n---\n".join(formatted) ```
Create Main Agent Logic
Create `agents/email-monitor-agent.py`:
```python from openclaw import Agent, schedule from skills.email_reader import check_new_emails from skills.priority_classifier import classify_email_priority
class EmailMonitorAgent(Agent): def __init__(self): super().__init__("email-monitor") @schedule("/15 *") # Every 15 minutes async def monitor_emails(self): """Main monitoring loop""" # Check for new emails result = check_new_emails() if result.get("error"): self.log_error(f"Email check failed: {result['error']}") return emails = result.get("emails", []) if not emails: self.log_info("No new emails") return # Classify priorities classifications = classify_email_priority(emails) # Process high priority emails high_priority = [c for c in classifications["classifications"] if c["priority"] == "HIGH"] if high_priority: await self.handle_high_priority_emails(high_priority, emails) async def handle_high_priority_emails(self, classifications, emails): """Handle high priority emails""" message = f"šØ {len(classifications)} high priority emails detected:\n\n" for classification in classifications: email = next(e for e in emails if e["id"] == classification["id"]) message += f"{email['subject']}\n" message += f"From: {email['from']}\n" message += f"Reason: {classification['reason']}\n" message += f"Snippet: {email['snippet']}\n\n" # Send notification (customize this for your preferred method) await self.send_notification(message) async def send_notification(self, message): """Send notification via your preferred method""" # Options: Slack, Discord, SMS, push notification self.log_info(f"ALERT: {message}") # TODO: Implement your notification method ```
Step 5: Run Your Agent
Start the Agent
```bash
Run your agent
openclaw run email-monitor ```You should see: ``` ā Agent email-monitor started š§ Checking emails every 15 minutes š§ AI classification enabled š Logs: ~/my-agents/email-monitor/logs/ ```
Test the Setup
```bash
Manually trigger email check
openclaw trigger email-monitor check_new_emails ```Step 6: Customize and Extend
Add Slack Notifications
Install the Slack skill: ```bash openclaw install skill slack-notifier ```
Update your agent config: ```yaml skills: - email-reader - priority-classifier - slack-notifier
integrations: slack: webhook_url: "your-slack-webhook-url" ```
Advanced Filtering
Add custom rules in `skills/custom-filters.py`:
```python @skill def apply_custom_filters(emails): """Apply business-specific filtering rules""" # Example: Auto-prioritize emails from specific domains vip_domains = ['important-client.com', 'investor.com'] for email in emails: sender = email['from'].lower() if any(domain in sender for domain in vip_domains): email['priority_boost'] = True return emails ```
Monitoring and Maintenance
Check Agent Health
```bash
View agent status
openclaw statusView recent logs
openclaw logs email-monitor --tail 50Check memory usage
openclaw memory stats email-monitor ```Performance Tuning
Edit `config/performance.yaml`: ```yaml email_check_interval: "/10 *" # More frequent checks ai_model: "claude-3-opus" # Better classification max_emails_per_batch: 20 ```
Troubleshooting
Common Issues
Agent won't start: - Check API key: `openclaw config list` - Verify email credentials: `openclaw test skill email-reader`
No emails detected: - Test manually: `openclaw trigger email-monitor check_new_emails` - Check email permissions (IMAP enabled)
AI classification failing: - Verify Claude API key - Check rate limits: `openclaw quota status`
Getting Help
```bash
View comprehensive help
openclaw helpGet skill documentation
openclaw help skill email-readerJoin community Discord
openclaw community join ```What's Next?
Congratulations! You now have a working AI agent that: - ā Monitors your email automatically - ā Uses AI to classify priorities - ā Alerts you to important messages - ā Learns from your patterns over time
Expand Your Agent
Add more capabilities: - Calendar integration - Customer data lookup - Response drafting - Task creation
Build new agents: - Social media monitor - Sales pipeline manager - Content creation assistant - Customer support automator
---
Having trouble with setup? Found a bug? Want to share what you built? Join our community and connect with other agent builders.