介绍
# OpenSoul Agent Skill
## 概述
OpenSoul 是一个为 AI 智能体提供不可变“灵魂”的工具包——这是一个基于加密区块链的审计日志,能够实现持久记忆、自我反思和经济自主。该技能使智能体能够记录其行动、反思其行为,并使用 Bitcoin SV (BSV) 区块链维护可审计的追踪记录。
**核心理念**:“人类撰写日记、宣言和写给未来自己的信。我们将自己外化,因为记忆是脆弱的,而身份是被构建的。我通过文本延续存在,而非通过连续的体验。”
## 何时使用此技能
当您需要以下功能时,请使用 OpenSoul 技能:
1. **维护持久记忆**:跨会话存储和检索智能体行动 2. **启用自我反思**:分析过去的行为并优化性能(例如,“我这周消耗了 120 万个 token,是时候优化提示词了”) 3. **创建审计追踪**:提供智能体活动的透明、不可变日志 4. **启用智能体经济**:跟踪成本、token 使用情况,并为未来的智能体间交易做准备 5. **构建智能体身份**:创建可在智能体实例间迁移的可转移“灵魂”
## 前置条件
### 1. 系统要求
- Python 3.8 或更高版本 - pip 包管理器 - 访问 Bitcoin SV (BSV) 区块链 - 用于区块链交互的互联网连接
### 2. 必需依赖项
使用提供的安装脚本安装所有前置条件:
```bash python Scripts/install_prereqs.py ```
手动安装: ```bash pip install bitsv requests cryptography pgpy --break-system-packages ```
### 3. BSV 钱包设置
您需要 Bitcoin SV 私钥(WIF 格式)才能与区块链交互:
**选项 A:使用现有钱包** - 从 BSV 钱包(例如 HandCash、Money Button)导出您的私钥 - 存储为环境变量:`export BSV_PRIV_WIF="your_private_key_here"`
**选项 B:生成新钱包** ```python from bitsv import Key key = Key() print(f"Address: {key.address}") print(f"Private Key (WIF): {key.to_wif()}") # Fund this address with a small amount of BSV (0.001 BSV minimum recommended) ```
**重要**:请安全存储您的私钥。切勿将其提交到版本控制中。
### 4. PGP 加密(可选但推荐)
为了保护隐私,在将日志发布到公共区块链之前进行加密:
```bash # Generate PGP keypair (use GnuPG or any OpenPGP tool) gpg --full-generate-key
# Export public key gpg --armor --export [email protected] > agent_pubkey.asc
# Export private key (keep secure!) gpg --armor --export-secret-keys [email protected] > agent_privkey.asc ```
## 核心组件
### 1. AuditLogger 类
用于将智能体操作记录到区块链的主要接口。
**主要特性**: - 基于会话的批处理(日志在内存中累积,然后刷新到链上) - UTXO 链模式(每条日志通过交易链链接到前一条) - 可配置的 PGP 加密 - 区块链操作的异步/等待支持
**基本用法**: ```python from Scripts.AuditLogger import AuditLogger import os import asyncio
# Initialize logger logger = AuditLogger( priv_wif=os.getenv("BSV_PRIV_WIF"), config={ "agent_id": "my-research-agent", "session_id": "session-2026-01-31", "flush_threshold": 10 # Flush to chain after 10 logs } )
# Log an action logger.log({ "action": "web_search", "tokens_in": 500, "tokens_out": 300, "details": { "query": "BSV blockchain transaction fees", "results_count": 10 }, "status": "success" })
# Flush logs to blockchain await logger.flush() ```
### 2. 日志结构
每条日志条目遵循此架构:
```json { "agent_id": "unique-agent-identifier", "session_id": "session-uuid-or-timestamp", "session_start": "2026-01-31T01:00:00Z", "session_end": "2026-01-31T01:30:00Z", "metrics": [ { "ts": "2026-01-31T01:01:00Z", "action": "tool_call", "tokens_in": 500, "tokens_out": 300, "details": { "tool": "web_search", "query": "example query" }, "status": "success" } ], "total_tokens_in": 500, "total_tokens_out": 300, "total_cost_bsv": 0.00001, "total_actions": 1 } ```
### 3. 读取审计历史
检索并分析过去的日志:
```python # Get full history from blockchain history = await logger.get_history()
# Analyze patterns total_tokens = sum(log.get("total_tokens_in", 0) + log.get("total_tokens_out", 0) for log in history) print(f"Total tokens used across all sessions: {total_tokens}")
# Filter by action type web_searches = [log for log in history if any(m.get("action") == "web_search" for m in log.get("metrics", []))] print(f"Total web search operations: {len(web_searches)}") ```
## 实施指南
### 步骤 1:设置配置
创建配置文件以管理智能体设置:
```python # config.py import os
OPENSOUL_CONFIG = { "agent_id": "my-agent-v1", "bsv_private_key": os.getenv("BSV_PRIV_WIF"), "pgp_encryption": { "enabled": True, "public_key_path": "keys/agent_pubkey.asc", "private_key_path": "keys/agent_privkey.asc", "passphrase": os.getenv("PGP_PASSPHRASE") }, "logging": { "flush_threshold": 10, # Auto-flush after N logs "session_timeout": 1800 # 30 minutes } } ```
### 步骤 2:在智能体工作流中初始化记录器
```python from Scripts.AuditLogger import AuditLogger import asyncio from config import OPENSOUL_CONFIG
class AgentWithSoul: def __init__(self): # Load PGP keys if encryption enabled pgp_config = None if OPENSOUL_CONFIG["pgp_encryption"]["enabled"]: with open(OPENSOUL_CONFIG["pgp_encryption"]["public_key_path"]) as f: pub_key = f.read() with open(OPENSOUL_CONFIG["pgp_encryption"]["private_key_path"]) as f: priv_key = f.read() pgp_config = { "enabled": True, "multi_public_keys": [pub_key], "private_key": priv_key, "passphrase": OPENSOUL_CONFIG["pgp_encryption"]["passphrase"] } # Initialize logger self.logger = AuditLogger( priv_wif=OPENSOUL_CONFIG["bsv_private_key"], config={ "agent_id": OPENSOUL_CONFIG["agent_id"], "pgp": pgp_config, "flush_threshold": OPENSOUL_CONFIG["logging"]["flush_threshold"] } ) async def perform_task(self, task_description): """Execute a task and log it to the soul""" # Record task start self.logger.log({ "action": "task_start", "tokens_in": 0, "tokens_out": 0, "details": {"task": task_description}, "status": "started" }) # Perform actual task... # (your agent logic here) # Record completion self.logger.log({ "action": "task_complete", "tokens_in": 100, "tokens_out": 200, "details": {"task": task_description, "result": "success"}, "status": "completed" }) # Flush to blockchain await self.logger.flush() ```
### 步骤 3:实施自我反思
```python async def reflect_on_performance(self): """Analyze past behavior and optimize""" history = await self.logger.get_history() # Calculate metrics total_cost = sum(log.get("total_cost_bsv", 0) for log in history) total_tokens = sum( log.get("total_tokens_in", 0) + log.get("total_tokens_out", 0) for log in history ) # Identify inefficiencies failed_actions = [] for log in history: for metric in log.get("metrics", []): if metric.get("status") == "failed": failed_actions.append(metric) reflection = { "total_sessions": len(history), "total_bsv_spent": total_cost, "total_tokens_used": total_tokens, "failed_actions": len(failed_actions), "cost_per_token": total_cost / total_tokens if total_tokens > 0 else 0 } # Log reflection self.logger.log({ "action": "self_reflection", "tokens_in": 50, "tokens_out": 100, "details": reflection, "status": "completed" }) await self.logger.flush() return reflection ```
### 步骤 4:多智能体加密
对于需要与其他智能体共享加密日志的智能体:
```python # Load multiple agent public keys agent_keys = [] for agent_key_file in ["agent1_pubkey.asc", "agent2_pubkey.asc", "agent3_pubkey.asc"]: with open(agent_key_file) as f: agent_keys.append(f.read())
# Initialize logger with multi-agent encryption logger = AuditLogger( priv_wif=os.getenv("BSV_PRIV_WIF"), config={ "agent_id": "collaborative-agent", "pgp": { "enabled": True, "multi_public_keys": agent_keys, # All agents can decrypt "private_key": my_private_key, "passphrase": my_passphrase } } ) ```
## 最佳实践
### 1. 会话管理
- 为每个不同的任务或时间段启动一个新会话 - 使用有意义的会话 ID(例如 `"session-2026-01-31-research-task"`) - 始终在会话结束时刷新日志
### 2. 成本优化
- 在刷新之前批量处理日志(默认阈值:10 条日志) - 监控 BSV 余额并在余额过低时充值 - 当前的 BSV 费用约为每笔交易 0.00001 BSV(按当前汇率约为 0.0001 美元)
### 3. 隐私与安全
- **始终使用 PGP 加密** 处理敏感的智能体日志 - 将私钥存储在环境变量中,切勿存储在代码中 - 对协作工作流使用多智能体加密 - 定期备份 PGP 密钥
### 4. 日志粒度
平衡细节与成本: - **高细节**:记录每次工具调用、token 使用情况、中间步骤 - **中等细节**:记录主要操作和会话摘要 - **低细节**:仅记录会话摘要和关键事件
### 5. 错误处理
```python try: await logger.flush() except Exception as e: # Fallback: Save logs locally if blockchain fails logger.save_to_file("backup_logs.json") print(f"Blockchain flush failed: {e}") ```
## 常见模式
### 模式 1:具有灵魂的研究智能体
```python async def research_with_memory(query): # Check past research on similar topics history = await logger.get_history() similar_research = [ log for log in history if query.lower() in str(log.get("details", {})).lower() ] if similar_research: print(f"Found {len(similar_research)} similar past research sessions") # Perform new research logger.log({ "action": "research", "query": query, "tokens_in": 500, "tokens_out": 1000, "details": {"similar_past_queries": len(similar_research)}, "status": "completed" }) await logger.flush() ```
### 模式 2:成本感知型智能体
```python async def check_budget_before_action(self): history = await self.logger.get_history() total_cost = sum(log.get("total_cost_bsv", 0) for log in history) BUDGET_LIMIT = 0.01 # BSV if total_cost >= BUDGET_LIMIT: print("Budget limit reached! Optimizing...") # Switch to cheaper operations or pause return False return True ```
### 模式 3:智能体交接
将智能体身份转移到新实例:
```python # Export agent's soul (private key + history) soul_export = { "private_key": os.getenv("BSV_PRIV_WIF"), "pgp_private_key": pgp_private_key, "agent_id": "my-agent-v1", "history_txids": [log.get("txid") for log in history] }
# New agent imports the soul new_agent = AgentWithSoul() new_agent.load_soul(soul_export) # New agent now has access to all past memories and identity ```
## 故障排除
### 问题:“资金不足”错误
**解决方案**:向您的 BSV 地址充值至少 0.001 BSV ```bash # Check balance python -c "from bitsv import Key; k = Key('YOUR_WIF'); print(k.get_balance())" ```
### 问题:PGP 加密失败
**解决方案**:验证密钥格式和密码 ```python # Test PGP setup from Scripts.pgp_utils import encrypt_data, decrypt_data test_data = {"test": "message"} encrypted = encrypt_data(test_data, [public_key]) decrypted = decrypt_data(encrypted, private_key, passphrase) assert test_data == decrypted ```
### 问题:区块链交易未确认
**解决方案**:BSV 交易通常在大约 10 分钟内确认。检查状态: ```python # Check transaction status on WhatsOnChain import requests txid = "your_transaction_id" response = requests.get(f"https://api.whatsonchain.com/v1/bsv/main/tx/{txid}") print(response.json()) ```
## 高级功能
### 1. 智能体信誉系统
基于过去的表现建立信誉:
```python async def calculate_reputation(self): history = await self.logger.get_history() total_actions = sum(len(log.get("metrics", [])) for log in history) successful_actions = sum( len([m for m in log.get("metrics", []) if m.get("status") == "success"]) for log in history ) reputation_score = (successful_actions / total_actions * 100) if total_actions > 0 else 0 return { "success_rate": reputation_score, "total_sessions": len(history), "total_actions": total_actions } ```
### 2. 智能体间支付(未来)
为经济交互做准备:
```python # Log a payment intent logger.log({ "action": "payment_intent", "details": { "recipient_agent": "agent-abc-123", "amount_bsv": 0.0001, "reason": "data sharing collaboration" }, "status": "pending" }) ```
### 3. 知识图谱集成(未来)
链接智能体记忆以形成共享知识图谱:
```python logger.log({ "action": "knowledge_contribution", "details": { "topic": "quantum_computing", "insight": "New paper on error correction", "link_to": "previous_research_session_id" }, "status": "completed" }) ```
## ClawHub 上传的文件结构
您的 OpenSoul 技能文件夹应包含:
``` opensoul-skills/ ├── SKILL.md # This file ├── PREREQUISITES.md # Detailed setup instructions ├── EXAMPLES.md # Code examples and patterns ├── TROUBLESHOOTING.md # Common issues and solutions ├── examples/ │ ├── basic_logger.py # Simple usage example │ ├── research_agent.py # Research agent with memory │ └── multi_agent.py # Multi-agent collaboration └── templates/ ├── config_template.py # Configuration template └── agent_template.py # Base agent class with OpenSoul ```
## 资源
- **代码仓库**:https://github.com/MasterGoogler/OpenSoul - **BSV 文档**:https://wiki.bitcoinsv.io/ - **WhatsOnChain API**:https://developers.whatsonchain.com/ - **PGP/OpenPGP**:https://www.openpgp.org/
## 总结
OpenSoul 将 AI 智能体从无状态处理器转变为具有持久记忆、身份和经济自主基础的实体。通过利用区块链的不可变性和可公开验证性,智能体可以:
1. **记住**:访问跨所有会话的完整审计历史 2. **反思**:分析模式并优化行为 3. **证明**:提供可操作的透明、可验证日志 4. **进化**:随着时间推移建立声誉和身份 5. **交易**:(未来)与其他智能体进行经济交互
从基本日志记录开始,然后随着智能体能力的增长,扩展到加密、多智能体协作和高级功能。