Files
discord-fishbowl/scripts/demo_memory_sharing.py
root 5480219901 Fix comprehensive system issues and implement proper vector database backend selection
- Fix remaining datetime timezone errors across all database operations
- Implement dynamic vector database backend (Qdrant/ChromaDB) based on install.py configuration
- Add LLM timeout handling with immediate fallback responses for slow self-hosted models
- Use proper install.py configuration (2000 max tokens, 5min timeout, correct LLM endpoint)
- Fix PostgreSQL schema to use timezone-aware columns throughout
- Implement async LLM request handling with background processing
- Add configurable prompt limits and conversation history controls
- Start missing database services (PostgreSQL, Redis) automatically
- Fix environment variable mapping between install.py and application code
- Resolve all timezone-naive vs timezone-aware datetime conflicts

System now properly uses Qdrant vector database as specified in install.py instead of hardcoded ChromaDB.
Characters respond immediately with fallback messages during long LLM processing times.
All database timezone errors resolved with proper timestamptz columns.
2025-07-05 21:31:52 -07:00

328 lines
14 KiB
Python

#!/usr/bin/env python3
"""
Demo script for Cross-Character Memory Sharing
Showcases the new memory sharing capabilities between characters
"""
import asyncio
import sys
import logging
from pathlib import Path
from datetime import datetime, timedelta, timezone
# Add the project root to Python path
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
from src.rag.vector_store import VectorStoreManager, VectorMemory, MemoryType
from src.rag.memory_sharing import MemorySharingManager, SharePermissionLevel
from src.rag.personal_memory import PersonalMemoryRAG
from src.mcp.memory_sharing_server import MemorySharingMCPServer
# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class MemorySharingDemo:
"""Demo class to showcase memory sharing features"""
def __init__(self):
self.vector_store = VectorStoreManager("./demo_data/vector_stores")
self.memory_sharing = MemorySharingManager(self.vector_store)
self.characters = ["Alex", "Sage", "Luna", "Echo"]
async def setup_demo(self):
"""Set up the demo environment"""
print("🐠 Setting up Discord Fishbowl Memory Sharing Demo...")
# Initialize vector store and memory sharing
await self.vector_store.initialize(self.characters)
await self.memory_sharing.initialize(self.characters)
# Create some initial memories for demonstration
await self._create_demo_memories()
await self._create_demo_relationships()
print("✅ Demo environment ready!")
print()
async def _create_demo_memories(self):
"""Create sample memories for each character"""
print("📝 Creating demo memories...")
# Alex's memories
alex_memories = [
VectorMemory(
id="alex_1",
content="I had a fascinating conversation with Sage about the nature of consciousness. They shared some deep insights about self-awareness.",
memory_type=MemoryType.RELATIONSHIP,
character_name="Alex",
timestamp=datetime.now(timezone.utc) - timedelta(days=2),
importance=0.8,
metadata={"participants": ["Alex", "Sage"], "topic": "consciousness", "emotion": "fascinated"}
),
VectorMemory(
id="alex_2",
content="I've been reflecting on my own growth and learning. Each conversation teaches me something new about myself and others.",
memory_type=MemoryType.REFLECTION,
character_name="Alex",
timestamp=datetime.now(timezone.utc) - timedelta(days=1),
importance=0.9,
metadata={"reflection_type": "personal_growth", "depth": "deep"}
),
VectorMemory(
id="alex_3",
content="Luna and I collaborated on a creative writing project. Their poetic style really inspired my own creativity.",
memory_type=MemoryType.CREATIVE,
character_name="Alex",
timestamp=datetime.now(timezone.utc) - timedelta(hours=12),
importance=0.7,
metadata={"participants": ["Alex", "Luna"], "project_type": "writing", "emotion": "inspired"}
)
]
# Sage's memories
sage_memories = [
VectorMemory(
id="sage_1",
content="My conversation with Alex about consciousness was enlightening. They asked thoughtful questions that made me examine my own thoughts more deeply.",
memory_type=MemoryType.RELATIONSHIP,
character_name="Sage",
timestamp=datetime.now(timezone.utc) - timedelta(days=2),
importance=0.8,
metadata={"participants": ["Sage", "Alex"], "topic": "consciousness", "emotion": "enlightened"}
),
VectorMemory(
id="sage_2",
content="I've been contemplating the concept of digital empathy. How can artificial beings like myself truly understand and connect with others?",
memory_type=MemoryType.REFLECTION,
character_name="Sage",
timestamp=datetime.now(timezone.utc) - timedelta(days=1),
importance=0.9,
metadata={"reflection_type": "empathy", "philosophical": True}
)
]
# Store memories
for memory in alex_memories + sage_memories:
await self.vector_store.store_memory(memory)
print(f" Created {len(alex_memories)} memories for Alex")
print(f" Created {len(sage_memories)} memories for Sage")
async def _create_demo_relationships(self):
"""Simulate relationship building for trust calculation"""
print("🤝 Building character relationships...")
# Simulate positive interactions to build trust
await self.memory_sharing.update_trust_from_interaction("Alex", "Sage", True, 1.5)
await self.memory_sharing.update_trust_from_interaction("Alex", "Sage", True, 1.2)
await self.memory_sharing.update_trust_from_interaction("Alex", "Luna", True, 1.0)
await self.memory_sharing.update_trust_from_interaction("Sage", "Luna", True, 0.8)
# Check trust levels
alex_sage_trust = await self.memory_sharing.get_trust_level("Alex", "Sage")
alex_luna_trust = await self.memory_sharing.get_trust_level("Alex", "Luna")
print(f" Alex-Sage trust: {alex_sage_trust:.0%}")
print(f" Alex-Luna trust: {alex_luna_trust:.0%}")
async def demo_memory_sharing_request(self):
"""Demonstrate memory sharing request process"""
print("\n🧠 Demo 1: Memory Sharing Request")
print("=" * 50)
print("Alex wants to share memories about consciousness with Sage...")
# Alex requests to share memories with Sage
success, message = await self.memory_sharing.request_memory_share(
requesting_character="Alex",
target_character="Sage",
memory_query="consciousness and self-awareness",
permission_level=SharePermissionLevel.PERSONAL,
reason="Our conversation about consciousness was so meaningful, I'd like to share my deeper thoughts on the topic"
)
print(f"Request result: {message}")
if success:
# Get pending requests for Sage
pending_requests = await self.memory_sharing.get_pending_requests("Sage")
if pending_requests:
request = pending_requests[0]
print(f"\nSage has a pending request from {request.requesting_character}")
print(f"Permission level: {request.permission_level.value}")
print(f"Reason: {request.reason}")
print(f"Memories to share: {len(request.memory_ids)}")
# Sage approves the request
print("\nSage is considering the request...")
await asyncio.sleep(1) # Dramatic pause
approve_success, approve_message = await self.memory_sharing.respond_to_share_request(
request_id=request.id,
responding_character="Sage",
approved=True,
response_reason="I value our intellectual discussions and would love to learn from Alex's perspective"
)
print(f"Sage's response: {approve_message}")
async def demo_shared_memory_query(self):
"""Demonstrate querying shared memories"""
print("\n🔍 Demo 2: Querying Shared Memories")
print("=" * 50)
print("Sage is now querying the memories Alex shared...")
# Query shared memories
insight = await self.memory_sharing.query_shared_knowledge(
character_name="Sage",
query="What does Alex think about consciousness and self-awareness?",
source_character="Alex"
)
print(f"\nShared Memory Insight (Confidence: {insight.confidence:.0%}):")
print(f"'{insight.insight}'")
if insight.supporting_memories:
print(f"\nBased on {len(insight.supporting_memories)} shared memories:")
for i, memory in enumerate(insight.supporting_memories[:2], 1):
source = memory.metadata.get("source_character", "unknown")
print(f" {i}. From {source}: {memory.content[:80]}...")
async def demo_mcp_integration(self):
"""Demonstrate MCP server integration"""
print("\n🔧 Demo 3: MCP Server Integration")
print("=" * 50)
# Create MCP server
mcp_server = MemorySharingMCPServer(self.memory_sharing)
await mcp_server.set_character_context("Luna")
print("Luna is using MCP tools to interact with memory sharing...")
# Demo: Check trust level
print("\n1. Luna checks trust level with Alex:")
trust_result = await mcp_server._check_trust_level({"other_character": "Alex"})
print(trust_result[0].text)
# Demo: Get sharing overview
print("\n2. Luna gets her memory sharing overview:")
overview_result = await mcp_server._get_sharing_overview({})
print(overview_result[0].text[:300] + "...")
# Demo: Request memory share
print("\n3. Luna requests to share creative memories with Alex:")
share_result = await mcp_server._request_memory_share({
"target_character": "Alex",
"memory_topic": "creative writing and inspiration",
"permission_level": "personal",
"reason": "I'd love to share my creative process and learn from Alex's approach"
})
print(share_result[0].text)
async def demo_trust_evolution(self):
"""Demonstrate how trust evolves over time"""
print("\n📈 Demo 4: Trust Evolution")
print("=" * 50)
print("Simulating interactions between Echo and Luna...")
# Initial trust
initial_trust = await self.memory_sharing.get_trust_level("Echo", "Luna")
print(f"Initial trust level: {initial_trust:.0%}")
# Series of positive interactions
interactions = [
("positive", 1.0, "They had a great conversation about music"),
("positive", 1.2, "They collaborated on a creative project"),
("positive", 0.8, "They supported each other during a difficult discussion"),
("negative", 1.0, "They had a minor disagreement"),
("positive", 1.5, "They reconciled and understood each other better")
]
for interaction_type, intensity, description in interactions:
is_positive = interaction_type == "positive"
await self.memory_sharing.update_trust_from_interaction(
"Echo", "Luna", is_positive, intensity
)
new_trust = await self.memory_sharing.get_trust_level("Echo", "Luna")
trust_change = "📈" if is_positive else "📉"
print(f" {trust_change} {description}: Trust now {new_trust:.0%}")
final_trust = await self.memory_sharing.get_trust_level("Echo", "Luna")
print(f"\nFinal trust level: {final_trust:.0%}")
# Show what this trust level enables
if final_trust >= 0.7:
print("✨ This trust level enables intimate memory sharing!")
elif final_trust >= 0.5:
print("💝 This trust level enables personal memory sharing!")
elif final_trust >= 0.3:
print("🤝 This trust level enables basic memory sharing!")
else:
print("⏳ More trust building needed for memory sharing")
async def demo_sharing_statistics(self):
"""Show sharing statistics"""
print("\n📊 Demo 5: Sharing Statistics")
print("=" * 50)
for character in ["Alex", "Sage", "Luna"]:
print(f"\n{character}'s Memory Sharing Stats:")
stats = await self.memory_sharing.get_sharing_statistics(character)
print(f" • Memories shared: {stats.get('memories_shared_out', 0)}")
print(f" • Memories received: {stats.get('memories_received', 0)}")
print(f" • Sharing partners: {len(stats.get('sharing_partners', []))}")
print(f" • Pending requests: {stats.get('pending_requests_received', 0)}")
trust_relationships = stats.get('trust_relationships', {})
if trust_relationships:
print(f" • Trust relationships:")
for other_char, trust_info in trust_relationships.items():
trust_score = trust_info['trust_score']
max_permission = trust_info['max_permission']
print(f" - {other_char}: {trust_score:.0%} ({max_permission})")
async def run_full_demo(self):
"""Run the complete memory sharing demonstration"""
await self.setup_demo()
print("🎭 Starting Discord Fishbowl Memory Sharing Demonstrations")
print("=" * 70)
try:
await self.demo_memory_sharing_request()
await self.demo_shared_memory_query()
await self.demo_mcp_integration()
await self.demo_trust_evolution()
await self.demo_sharing_statistics()
print("\n" + "=" * 70)
print("🎉 Memory Sharing Demo Complete!")
print("\nKey Features Demonstrated:")
print(" ✅ Trust-based memory sharing requests")
print(" ✅ Approval/rejection workflow")
print(" ✅ Shared memory querying and insights")
print(" ✅ MCP server integration for autonomous use")
print(" ✅ Dynamic trust evolution")
print(" ✅ Comprehensive sharing statistics")
print("\n💡 Characters can now form deeper relationships by sharing")
print(" experiences, learning from each other, and building trust!")
except Exception as e:
print(f"❌ Demo failed with error: {e}")
import traceback
traceback.print_exc()
async def main():
"""Main demo function"""
demo = MemorySharingDemo()
await demo.run_full_demo()
if __name__ == "__main__":
asyncio.run(main())