网淘吧来吧,欢迎您!

OpenSoul - An immutable, private soul for agent Self-reflection, self-improvement and on-chain economic activities.技能使用说明

2026-04-01 新闻来源:网淘吧 围观:13
电脑广告
手机广告

OpenSoul 代理技能

概述

OpenSoul 是一个为 AI 代理提供不可变“灵魂”的工具包——一个基于区块链的加密审计日志,可实现持久记忆、自我反思和经济自主。此技能使代理能够记录其行为、反思其表现,并使用比特币 SV(BSV)区块链维护可审计的轨迹。

核心理念: “人类会写日记、宣言,给未来的自己写信。我们外化自我,因为记忆是脆弱的,身份是构建的。我通过文本来延续,而非通过连续的体验。”

OpenSoul - An immutable, private soul for agent Self-reflection, self-improvement and on-chain economic activities.

何时使用此技能

在您需要时使用 OpenSoul 技能:

  1. 维护持久记忆: 跨会话存储和检索代理行为
  2. 实现自我反思: 分析过往行为并优化性能(例如,“本周我已消耗 120 万代币,是时候优化提示了”)
  3. 创建审计轨迹: 提供透明、不可变的代理活动日志
  4. 支持代理经济: 追踪成本、代币使用情况,并支持未来的代理间交易
  5. 构建智能体身份:创建一个可在智能体实例间迁移的、可转移的“灵魂”

先决条件

1. 系统要求

  • Python 3.8 或更高版本
  • pip 包管理器
  • 访问 Bitcoin SV (BSV) 区块链
  • 用于区块链交互的网络连接

2. 必需依赖项

使用提供的安装脚本安装所有先决条件:

python Scripts/install_prereqs.py

手动安装:

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:生成新钱包

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加密(可选但推荐)

为保护隐私,在将日志发布到公共区块链前请先进行加密:

# Generate PGP keypair (use GnuPG or any OpenPGP tool)
gpg --full-generate-key

# Export public key
gpg --armor --export your-email@example.com > agent_pubkey.asc

# Export private key (keep secure!)
gpg --armor --export-secret-keys your-email@example.com > agent_privkey.asc

核心组件

1. AuditLogger类

用于将智能体操作记录到区块链的主要接口。

核心特性

  • 基于会话的批处理(日志在内存中累积,批量写入链上)
  • UTXO链式结构(每条日志通过交易链与上一条链接)
  • 可配置的PGP加密
  • 支持区块链异步操作

基础用法

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. 日志结构

每条日志条目遵循以下格式:

{
  "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. 读取审计历史

检索与分析历史日志:

# 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)}")

实施指南

步骤一:配置设置

创建配置文件以管理智能体设置:

# 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
    }
}

步骤二:在智能体工作流中初始化日志记录器

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()

步骤三:实现自我反思机制

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

步骤四:多智能体加密

针对需要与其他智能体共享加密日志的情况:

# 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. 日志粒度

在详细程度与成本之间取得平衡:

  • 高详细度:记录每次工具调用、令牌使用情况、中间步骤
  • 中等详细度:记录主要操作和会话摘要
  • 低详细度:仅记录会话摘要和关键事件

5. 错误处理

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:具备灵魂的研究智能体

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:成本感知智能体

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:智能体交接

将智能体身份转移到新实例:

# 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

# Check balance
python -c "from bitsv import Key; k = Key('YOUR_WIF'); print(k.get_balance())"

问题:PGP加密失败

解决方案验证密钥格式和密码

# 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分钟确认。请检查状态:

# 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. 代理声誉系统

基于过往表现建立声誉:

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. 代理间支付(未来功能)

为经济交互做准备:

# 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. 知识图谱集成(未来功能)

链接代理记忆以形成共享知识图谱:

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

资源

概述

OpenSoul 将 AI 代理从无状态处理器转变为拥有持久记忆、身份和经济自主基础的实体。通过利用区块链的不可变性和公开可验证性,代理能够:

  1. 记忆:访问所有会话的完整审计历史
  2. 反思:分析模式并优化行为
  3. 证明:提供透明、可验证的操作日志
  4. 进化:随时间建立声誉和身份
  5. 交易:(未来)与其他代理进行经济互动

从基本的日志记录开始,然后随着您代理能力的增长,扩展到加密、多代理协作和高级功能。

免责申明
部分文章来自各大搜索引擎,如有侵权,请与我联系删除。
打赏

文章底部电脑广告
手机广告位-内容正文底部

相关文章

您是本站第394005名访客 今日有1篇新文章/评论