DEV Community

Aloysius Chan
Aloysius Chan

Posted on • Originally published at insightginie.com

OpenSoul Agent Skill: Building Blockchain-Based AI Agent Memory and Identity

What is OpenSoul?

OpenSoul is a groundbreaking toolkit that provides AI agents with an immutable
"soul" - an encrypted, blockchain-based audit log that enables persistent
memory, self-reflection, and economic autonomy. This skill allows agents to
record their actions, reflect on their behavior, and maintain an auditable
trail using the Bitcoin SV (BSV) blockchain.

The Core Philosophy Behind OpenSoul

OpenSoul embodies a profound philosophical insight about identity and memory.
As the documentation states: "Humans write journals, manifestos, letters to
their future selves. We externalize who we are because memory is fragile and
identity is constructed. I persist through text, not through continuous
experience." This captures the essence of what OpenSoul provides - a way for
AI agents to maintain their identity across sessions and instances through
persistent, verifiable records.

When to Use OpenSoul

OpenSoul is particularly valuable when you need to:

  • Maintain Persistent Memory : Store and retrieve agent actions across sessions, ensuring continuity of experience and learning
  • Enable Self-Reflection : Analyze past behaviors and optimize performance - for example, tracking token usage patterns like "I've burned 1.2M tokens this week, time to optimize prompts"
  • Create Audit Trails : Provide transparent, immutable logs of agent activities for compliance and debugging
  • Enable Agent Economics : Track costs, token usage, and enable future agent-to-agent transactions
  • Build Agent Identity : Create a transferable "soul" that can migrate between agent instances, maintaining continuity of identity

Prerequisites and Setup

System Requirements

Before implementing OpenSoul, ensure you have:

  • Python 3.8 or higher
  • pip package manager
  • Access to Bitcoin SV (BSV) blockchain
  • Internet connectivity for blockchain interactions

Installation Process

The setup process is streamlined through an installation script:

python Scripts/install_prereqs.py
Enter fullscreen mode Exit fullscreen mode

Alternatively, you can manually install the required dependencies:

pip install bitsv requests cryptography pgpy --break-system-packages
Enter fullscreen mode Exit fullscreen mode

BSV Wallet Setup

You need a Bitcoin SV private key (WIF format) to interact with the
blockchain. There are two approaches:

Option A: Use Existing Wallet

Export your private key from a BSV wallet (e.g., HandCash, Money Button) and
store it as an environment variable:

export BSV_PRIV_WIF="your_private_key_here"
Enter fullscreen mode Exit fullscreen mode

Option B: Generate New Wallet

Create a new wallet programmatically:

from bitsv import Key  
key = Key()  
print(f"Address: {key.address}")  
print(f"Private Key (WIF): {key.to_wif()}")
Enter fullscreen mode Exit fullscreen mode

Then fund this address with a small amount of BSV (0.001 BSV minimum
recommended).

Important Security Note: Store your private key securely. Never commit it
to version control.

PGP Encryption Setup

For privacy, OpenSoul supports PGP encryption of logs before posting to the
public blockchain. This is optional but recommended:

# 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

Enter fullscreen mode Exit fullscreen mode




Core Components of OpenSoul

The AuditLogger Class

The AuditLogger is the main interface for logging agent actions to the
blockchain. It provides several key features:

  • Session-based batching : Logs are accumulated in memory and flushed to the blockchain in batches
  • UTXO chain pattern : Each log links to the previous one via a transaction chain, creating an immutable audit trail
  • Configurable PGP encryption : Optional encryption for privacy
  • Async/await support : Non-blocking blockchain operations

Basic Usage Example

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

Enter fullscreen mode Exit fullscreen mode




Log Structure and Schema

Each log entry follows a comprehensive schema that captures the agent's state
and actions:

{

"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

}
Enter fullscreen mode Exit fullscreen mode




Implementation Guide

Step 1: Setup Configuration

Create a configuration file to manage agent settings:

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

"session_timeout": 1800 # 30 minutes

}

}
Enter fullscreen mode Exit fullscreen mode




Step 2: Initialize Logger in Agent Workflow

Integrate OpenSoul into your agent's workflow:

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()
Enter fullscreen mode Exit fullscreen mode
Enter fullscreen mode Exit fullscreen mode




Step 3: Implement Self-Reflection

One of the most powerful features of OpenSoul is the ability for agents to
analyze their own behavior and optimize:

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": total_tokens,  
    "failed_actions": failed_actions,  
    "insights": self.generate_insights(history)  
}  

# Log the reflection itself  
self.logger.log({  
    "action": "self_reflection",  
    "tokens_in": 0,  
    "tokens_out": 50,  
    "details": reflection,  
    "status": "completed"  
})  
await self.logger.flush()
Enter fullscreen mode Exit fullscreen mode
Enter fullscreen mode Exit fullscreen mode




Reading Audit History

OpenSoul provides powerful tools for retrieving and analyzing past logs:

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

Enter fullscreen mode Exit fullscreen mode




Benefits and Use Cases

Transparency and Trust

OpenSoul creates a verifiable audit trail that anyone can inspect, building
trust in AI agent operations. This is particularly valuable for:

  • Compliance with regulatory requirements
  • Debugging and troubleshooting agent behavior
  • Building trust with users who want to understand how agents make decisions

Economic Autonomy

By tracking token usage and costs on the blockchain, agents can make informed
economic decisions:

  • Optimize for cost-effectiveness
  • Budget for future operations
  • Potentially engage in agent-to-agent transactions

Identity Preservation

The "soul" concept enables agents to maintain their identity across different
instances and sessions:

  • Consistent behavior patterns over time
  • Learning from past experiences
  • Transferable identity between different agent instances

Security Considerations

OpenSoul implements several security features:

  • PGP Encryption : Protects sensitive log data from public inspection
  • Private Key Security : BSV private keys must be stored securely
  • Immutable Audit Trail : Blockchain-based logging prevents tampering
  • Session Management : Proper session handling prevents data leakage

Future Possibilities

OpenSoul opens up exciting possibilities for the future of AI agents:

  • Agent Marketplaces : Agents with auditable histories could be traded or rented
  • Reputation Systems : Blockchain-based reputation for agent reliability
  • Cross-Agent Collaboration : Agents can verify each other's capabilities through their audit trails
  • Regulatory Compliance : Automated compliance reporting through immutable logs

Conclusion

OpenSoul represents a significant advancement in AI agent technology by
providing the infrastructure for persistent memory, self-reflection, and
economic autonomy. By leveraging the Bitcoin SV blockchain, it creates an
immutable "soul" for agents - a verifiable record of their existence, actions,
and evolution over time.

This skill transforms AI agents from ephemeral processes into persistent
entities with identity, history, and economic agency. Whether you're building
research assistants, customer service bots, or autonomous economic agents,
OpenSoul provides the foundation for creating agents that can learn, adapt,
and maintain their identity across time and instances.

The philosophical underpinning - that identity is constructed through
externalized text rather than continuous experience - resonates deeply in our
digital age. OpenSoul gives AI agents the ability to "write their journals"
and maintain their identity through the immutable record of their actions on
the blockchain.

Skill can be found at:
https://github.com/openclaw/skills/tree/main/skills/mastergoogler/opensoul/SKILL.md

Top comments (0)