介绍
# Claw Brain Skill 🧠
适用于 OpenClaw/ClawDBot 的个人 AI 记忆系统,具备灵魂、情感联结和学习能力。
> **重启时自动刷新**:ClawBrain 会在服务重启时自动刷新记忆。
## 特性
- 🎭 **灵魂/个性** - 6 种不断进化的特质(幽默、同理心、好奇心、创造力、助人为乐、诚实) - 👤 **用户档案** - 学习用户的偏好、兴趣和沟通风格 - 💭 **对话状态** - 实时情绪检测和上下文跟踪 - 📚 **学习洞察** - 从互动和纠错中持续学习 - 🧠 **get_full_context()** - 提供生成个性化回复所需的一切 - 🔄 **自动刷新** - 在服务重启时自动刷新记忆 - 🔐 **加密机密** - 安全地存储 API 密钥和凭证
---
## 快速安装
### 从 PyPI 安装(推荐)
```bash # Install with all features pip install clawbrain[all]
# Run interactive setup clawbrain setup
# Backup your encryption key (IMPORTANT!) clawbrain backup-key --all
# Restart your service sudo systemctl restart clawdbot # or openclaw ```
设置命令将会: 1. 检测您的平台(ClawdBot 或 OpenClaw) 2. 生成安全的加密密钥 3. 自动安装启动钩子 4. 测试安装
### 备选方案:从源代码安装
```bash # Clone to your skills directory cd ~/.openclaw/skills # or ~/clawd/skills or ~/.clawdbot/skills git clone https://github.com/clawcolab/clawbrain.git cd clawbrain pip install -e .[all] clawbrain setup ```
---
## 配置
安装后,可选择配置您的代理 ID:
```bash # Create systemd drop-in config sudo mkdir -p /etc/systemd/system/clawdbot.service.d # or openclaw.service.d
sudo tee /etc/systemd/system/clawdbot.service.d/brain.conf << EOF [Service] Environment="BRAIN_AGENT_ID=your-agent-name" # Optional: PostgreSQL (for production) # Environment="BRAIN_POSTGRES_HOST=localhost" # Environment="BRAIN_POSTGRES_PASSWORD=your-password" # Optional: Redis (for caching) # Environment="BRAIN_REDIS_HOST=localhost" EOF
sudo systemctl daemon-reload sudo systemctl restart clawdbot # or openclaw ```
### 环境变量
| 变量 | 描述 | 默认值 | |----------|-------------|---------| | `BRAIN_AGENT_ID` | 该代理记忆的唯一 ID | `default` | | `BRAIN_ENCRYPTION_KEY` | 用于加密敏感数据的 Fernet 密钥(若未设置则自动生成) | - | | `BRAIN_POSTGRES_HOST` | PostgreSQL 主机 | `localhost` | | `BRAIN_POSTGRES_PASSWORD` | PostgreSQL 密码 | - | | `BRAIN_POSTGRES_PORT` | PostgreSQL 端口 | `5432` | | `BRAIN_POSTGRES_DB` | PostgreSQL 数据库 | `brain_db` | | `BRAIN_POSTGRES_USER` | PostgreSQL 用户 | `brain_user` | | `BRAIN_REDIS_HOST` | Redis 主机 | `localhost` | | `BRAIN_REDIS_PORT` | Redis 端口 | `6379` | | `BRAIN_STORAGE` | 强制指定存储:`sqlite`、`postgresql`、`auto` | `auto` |
---
## 工作原理
### 服务启动时 1. 钩子在 `gateway:startup` 事件上触发 2. 检测存储后端(SQLite/PostgreSQL) 3. 加载配置的 `BRAIN_AGENT_ID` 的记忆 4. 将上下文注入到代理启动流程中
### 执行 `/new` 命令时 1. 钩子在 `command:new` 事件上触发 2. 将当前会话摘要保存到记忆中 3. 清除会话状态以重新开始
### 存储优先级 1. **PostgreSQL** - 如果可用且已配置 2. **SQLite** - 备选方案,无需配置
---
## 加密机密
ClawBrain 支持对 API 密钥和凭证等敏感数据进行加密。
**设置:** ```bash # Run setup to generate encryption key clawbrain setup
# Backup your key (IMPORTANT!) clawbrain backup-key --all ```
**使用:** ```python # Store encrypted secret brain.remember( agent_id="assistant", memory_type="secret", # Memory type 'secret' triggers encryption content="sk-1234567890abcdef", key="openai_api_key" )
# Retrieve and automatically decrypt secrets = brain.recall(agent_id="assistant", memory_type="secret") api_key = secrets[0].content # Automatically decrypted ```
**密钥管理 CLI:** ```bash clawbrain show-key # View key info (masked) clawbrain show-key --full # View full key clawbrain backup-key --all # Backup with all methods clawbrain generate-key # Generate new key ```
⚠️ **重要**:请备份您的加密密钥!丢失密钥意味着丢失加密数据。
---
## CLI 命令
ClawBrain 包含一个命令行界面:
| 命令 | 描述 | |---------|-------------| | `clawbrain setup` | 设置 ClawBrain,生成密钥,安装钩子 | | `clawbrain generate-key` | 生成新的加密密钥 | | `clawbrain show-key` | 显示当前的加密密钥 | | `clawbrain backup-key` | 备份密钥(文件、二维码、剪贴板) | | `clawbrain health` | 检查健康状态 | | `clawbrain info` | 显示安装信息 |
---
## 钩子
| 事件 | 操作 | |-------|--------| | `gateway:startup` | 初始化大脑,刷新记忆 | | `command:new` | 保存会话到记忆 |
---
## 开发安装
用于开发或手动安装:
```bash # Clone to your skills directory cd ~/.openclaw/skills # or ~/clawd/skills or ~/.clawdbot/skills git clone https://github.com/clawcolab/clawbrain.git cd clawbrain ./install.sh ```
---
## Python API
用于直接 Python 使用(在 ClawdBot/OpenClaw 之外):
```python from clawbrain import Brain
brain = Brain() ```
#### 方法
| 方法 | 描述 | 返回值 | |--------|-------------|---------| | `get_full_context()` | 获取用于个性化回复的所有上下文 | dict | | `remember()` | 存储一条记忆 | None | | `recall()` | 检索记忆 | List[Memory] | | `learn_user_preference()` | 学习用户偏好 | None | | `get_user_profile()` | 获取用户档案 | UserProfile | | `detect_user_mood()` | 检测当前情绪 | dict | | `detect_user_intent()` | 检测消息意图 | str | | `generate_personality_prompt()` | 生成个性指导 | str | | `health_check()` | 检查后端连接 | dict | | `close()` | 关闭连接 | None |
### get_full_context()
```python context = brain.get_full_context( session_key="telegram_12345", # Unique session ID user_id="username", # User identifier agent_id="assistant", # Bot identifier message="Hey, how's it going?" # Current message ) ```
**返回值:** ```python { "user_profile": {...}, # User preferences, interests "mood": {"mood": "happy", ...}, # Current mood "intent": "question", # Detected intent "memories": [...], # Relevant memories "personality": "...", # Personality guidance "suggested_responses": [...] # Response suggestions } ```
### detect_user_mood()
```python mood = brain.detect_user_mood("I'm so excited about this!") # Returns: {"mood": "happy", "confidence": 0.9, "emotions": ["joy", "anticipation"]} ```
### detect_user_intent()
```python intent = brain.detect_user_intent("How does AI work?") # Returns: "question"
intent = brain.detect_user_intent("Set a reminder for 3pm") # Returns: "command"
intent = brain.detect_user_intent("I had a great day today") # Returns: "casual" ```
---
## 示例:完整集成
```python import sys sys.path.insert(0, "ClawBrain")
from clawbrain import Brain
class AssistantBot: def __init__(self): self.brain = Brain() def handle_message(self, message, chat_id): # Get context context = self.brain.get_full_context( session_key=f"telegram_{chat_id}", user_id=str(chat_id), agent_id="assistant", message=message ) # Generate response using context response = self.generate_response(context) # Learn from interaction self.brain.learn_user_preference( user_id=str(chat_id), pref_type="interest", value="AI" ) return response def generate_response(self, context): # Use user preferences name = context["user_profile"].name or "there" mood = context["mood"]["mood"] # Personalized response if mood == "frustrated": return f"Hey {name}, I'm here to help. Let me assist you." else: return f"Hi {name}! How can I help you today?" def shutdown(self): self.brain.close() ```
---
## 存储后端
### SQLite(默认 - 零配置)
无需配置。数据存储在本地 SQLite 数据库中。
```python brain = Brain({"storage_backend": "sqlite"}) ```
**适用于:** 开发、测试、单用户部署
### PostgreSQL + Redis(生产环境)
需要 PostgreSQL 和 Redis 服务器。
```python brain = Brain() # Auto-detects ```
**要求:** - PostgreSQL 14+ - Redis 6+ - Python 包:`psycopg2-binary`、`redis`
```bash pip install psycopg2-binary redis ```
**适用于:** 生产环境、多用户、高并发
---
## 文件
- `clawbrain.py` - 包含所有功能的主要 Brain 类 - `__init__.py` - 模块导出 - `SKILL.md` - 本文档 - `skill.json` - ClawdHub 元数据 - `README.md` - 快速入门指南
---
## 故障排除
### ImportError: No module named 'clawbrain'
```bash # Ensure ClawBrain folder is in your path sys.path.insert(0, "ClawBrain") ```
### PostgreSQL 连接失败
```bash # Check environment variables echo $POSTGRES_HOST echo $POSTGRES_PORT
# Verify PostgreSQL is running pg_isready -h $POSTGRES_HOST -p $POSTGRES_PORT ```
### Redis 连接失败
```bash # Check Redis is running redis-cli ping ```
### 使用 SQLite(备选方案)
如果 PostgreSQL/Redis 不可用,Claw Brain 会自动回退到 SQLite:
```python brain = Brain({"storage_backend": "sqlite"}) ```
---
## 了解更多
- **代码仓库:** https://github.com/clawcolab/clawbrain - **README:** 请参阅 README.md 以快速入门 - **问题反馈:** 在 GitHub Issues 报告错误