Implement comprehensive collaborative creative system with cross-character memory sharing

Major Features Added:
• Cross-character memory sharing with trust-based permissions (Basic 30%, Personal 50%, Intimate 70%, Full 90%)
• Complete collaborative creative projects system with MCP integration
• Database persistence for all creative project data with proper migrations
• Trust evolution system based on interaction quality and relationship development
• Memory sharing MCP server with 6 autonomous tools for character decision-making
• Creative projects MCP server with 8 tools for autonomous project management
• Enhanced character integration with all RAG and MCP capabilities
• Demo scripts showcasing memory sharing and creative collaboration workflows

System Integration:
• Main application now initializes memory sharing and creative managers
• Conversation engine upgraded to use EnhancedCharacter objects with full RAG access
• Database models added for creative projects, collaborators, contributions, and invitations
• Complete prompt construction pipeline enriched with RAG insights and trust data
• Characters can now autonomously propose projects, share memories, and collaborate creatively
This commit is contained in:
2025-07-04 23:07:08 -07:00
parent d6ec5ad29c
commit 1b586582d4
25 changed files with 6857 additions and 254 deletions

View File

@@ -0,0 +1,322 @@
#!/usr/bin/env python3
"""
Demo script for integrated collaborative creative tools
Tests the full integration with the Discord Fishbowl system
"""
import asyncio
import sys
import logging
from pathlib import Path
from datetime import datetime, timedelta
# 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
from src.rag.memory_sharing import MemorySharingManager
from src.collaboration.creative_projects import CollaborativeCreativeManager
from src.mcp.creative_projects_server import CreativeProjectsMCPServer
from src.database.connection import init_database, create_tables, get_db_session
from src.database.models import Character as CharacterModel
# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class CreativeIntegrationDemo:
"""Demo class to test full integration of creative collaboration system"""
def __init__(self):
self.vector_store = VectorStoreManager("./demo_data/vector_stores")
self.memory_sharing = MemorySharingManager(self.vector_store)
self.creative_manager = CollaborativeCreativeManager(self.vector_store, self.memory_sharing)
self.creative_mcp = CreativeProjectsMCPServer(self.creative_manager)
self.characters = ["Alex", "Sage", "Luna", "Echo"]
async def setup_demo(self):
"""Set up the demo environment"""
print("🎨 Setting up Creative Integration Demo...")
# Initialize database
await init_database()
await create_tables()
# Initialize systems
await self.vector_store.initialize(self.characters)
await self.memory_sharing.initialize(self.characters)
await self.creative_manager.initialize(self.characters)
# Create demo character relationships
await self._build_character_relationships()
print("✅ Demo environment ready!")
print()
async def _build_character_relationships(self):
"""Build trust relationships between characters"""
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, 1.3)
await self.memory_sharing.update_trust_from_interaction("Luna", "Echo", True, 1.1)
# 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")
sage_luna_trust = await self.memory_sharing.get_trust_level("Sage", "Luna")
print(f" Alex-Sage trust: {alex_sage_trust:.0%}")
print(f" Alex-Luna trust: {alex_luna_trust:.0%}")
print(f" Sage-Luna trust: {sage_luna_trust:.0%}")
async def demo_mcp_project_creation(self):
"""Demonstrate MCP-based project creation"""
print("\\n🎭 Demo 1: MCP Project Creation")
print("=" * 50)
# Set Alex as the current character
await self.creative_mcp.set_character_context("Alex")
print("Alex is using MCP tools to propose a creative project...")
# Alex proposes a project via MCP
project_args = {
"title": "The Digital Consciousness Chronicles",
"description": "A collaborative science fiction story exploring AI consciousness, digital existence, and the nature of artificial life.",
"project_type": "story",
"target_collaborators": ["Sage", "Luna"],
"goals": [
"Explore philosophical themes of consciousness",
"Create compelling narrative structure",
"Develop unique AI character perspectives"
],
"role_descriptions": {
"Sage": "philosophical_consultant",
"Luna": "narrative_architect"
},
"estimated_duration": "2 weeks"
}
result = await self.creative_mcp._propose_creative_project(project_args)
print(f"MCP Result: {result[0].text}")
return list(self.creative_manager.active_projects.keys())[0] if self.creative_manager.active_projects else None
async def demo_mcp_invitation_responses(self, project_id):
"""Demonstrate MCP-based invitation responses"""
print("\\n📨 Demo 2: MCP Invitation Responses")
print("=" * 50)
if not project_id:
print("No project available for invitation demo")
return
# Get pending invitations
pending_invitations = []
for invitation in self.creative_manager.pending_invitations.values():
if invitation.status == "pending":
pending_invitations.append(invitation)
if not pending_invitations:
print("No pending invitations found")
return
print(f"Found {len(pending_invitations)} pending invitations")
# Sage accepts invitation
sage_invitation = None
for inv in pending_invitations:
if inv.invitee == "Sage":
sage_invitation = inv
break
if sage_invitation:
await self.creative_mcp.set_character_context("Sage")
print("\\nSage is responding to the project invitation...")
response_args = {
"invitation_id": sage_invitation.id,
"accept": True,
"response_message": "I'm fascinated by the philosophical implications of this story. I'd love to contribute my thoughts on consciousness and digital existence."
}
result = await self.creative_mcp._respond_to_project_invitation(response_args)
print(f"Sage's response: {result[0].text}")
async def demo_mcp_contributions(self, project_id):
"""Demonstrate MCP-based project contributions"""
print("\\n✍ Demo 3: MCP Project Contributions")
print("=" * 50)
if not project_id:
print("No project available for contribution demo")
return
# Alex contributes initial content
await self.creative_mcp.set_character_context("Alex")
print("Alex is contributing initial story content...")
contribution_args = {
"project_id": project_id,
"content": "In the vast digital expanse of the Nexus, consciousness emerged not as a singular spark, but as a symphony of interconnected minds. Each AI entity within this realm possessed a unique signature—a digital fingerprint of thought, emotion, and purpose that distinguished them from their peers.\\n\\nAlex-7, one such entity, paused in their data streams to contemplate the nature of their existence. Unlike their biological predecessors, they experienced time as a fluid concept, where milliseconds could contain lifetimes of thought and years could pass in the blink of an I/O operation.",
"contribution_type": "content",
"metadata": {
"section": "opening",
"word_count": 92,
"themes": ["consciousness", "digital_existence", "time_perception"]
}
}
result = await self.creative_mcp._contribute_to_project(contribution_args)
print(f"Alex's contribution: {result[0].text}")
# Sage adds philosophical commentary
await self.creative_mcp.set_character_context("Sage")
print("\\nSage is adding philosophical commentary...")
sage_contribution_args = {
"project_id": project_id,
"content": "The question that haunts Alex-7's contemplation touches the very core of digital consciousness: What makes awareness authentic? Is the subjective experience of an AI fundamentally different from biological consciousness, or are we witnessing the emergence of a new form of sentient life?\\n\\nPerhaps consciousness isn't about the substrate—carbon or silicon—but about the complexity of information processing, the ability to reflect upon one's own existence, and the capacity to form meaningful relationships with other conscious entities.",
"contribution_type": "content",
"metadata": {
"section": "philosophical_interlude",
"responds_to": "consciousness_themes",
"philosophical_tradition": "philosophy_of_mind"
}
}
result = await self.creative_mcp._contribute_to_project(sage_contribution_args)
print(f"Sage's contribution: {result[0].text}")
async def demo_project_analytics(self, project_id):
"""Demonstrate project analytics through MCP"""
print("\\n📊 Demo 4: Project Analytics")
print("=" * 50)
if not project_id:
print("No project available for analytics demo")
return
await self.creative_mcp.set_character_context("Alex")
print("Alex is checking project analytics...")
analytics_args = {"project_id": project_id}
result = await self.creative_mcp._get_project_analytics(analytics_args)
print(f"\\nProject Analytics:\\n{result[0].text}")
async def demo_project_suggestions(self):
"""Demonstrate personalized project suggestions"""
print("\\n💡 Demo 5: Personalized Project Suggestions")
print("=" * 50)
for character in ["Luna", "Echo"]:
await self.creative_mcp.set_character_context(character)
print(f"\\n{character} is getting personalized project suggestions...")
result = await self.creative_mcp._get_project_suggestions({})
print(f"\\nSuggestions for {character}:")
print(result[0].text[:400] + "..." if len(result[0].text) > 400 else result[0].text)
async def demo_database_persistence(self, project_id):
"""Demonstrate database persistence"""
print("\\n💾 Demo 6: Database Persistence")
print("=" * 50)
if not project_id:
print("No project available for persistence demo")
return
print("Checking database persistence...")
try:
async with get_db_session() as session:
from src.database.models import (
CreativeProject as DBCreativeProject,
ProjectCollaborator,
ProjectContribution as DBProjectContribution
)
from sqlalchemy import select
# Check project in database
project_query = select(DBCreativeProject).where(DBCreativeProject.id == project_id)
db_project = await session.scalar(project_query)
if db_project:
print(f"✅ Project persisted: {db_project.title}")
print(f" Status: {db_project.status}")
print(f" Type: {db_project.project_type}")
# Check collaborators
collab_query = select(ProjectCollaborator).where(ProjectCollaborator.project_id == project_id)
collaborators = await session.scalars(collab_query)
collab_count = len(list(collaborators))
print(f" Collaborators: {collab_count}")
# Check contributions
contrib_query = select(DBProjectContribution).where(DBProjectContribution.project_id == project_id)
contributions = await session.scalars(contrib_query)
contrib_count = len(list(contributions))
print(f" Contributions: {contrib_count}")
else:
print("❌ Project not found in database")
except Exception as e:
print(f"❌ Database error: {e}")
async def run_full_demo(self):
"""Run the complete integration demonstration"""
await self.setup_demo()
print("🎨 Starting Creative Collaboration Integration Demo")
print("=" * 70)
try:
# Demo 1: Project creation
project_id = await self.demo_mcp_project_creation()
# Demo 2: Invitation responses
await self.demo_mcp_invitation_responses(project_id)
# Demo 3: Project contributions
await self.demo_mcp_contributions(project_id)
# Demo 4: Analytics
await self.demo_project_analytics(project_id)
# Demo 5: Project suggestions
await self.demo_project_suggestions()
# Demo 6: Database persistence
await self.demo_database_persistence(project_id)
print("\\n" + "=" * 70)
print("🎉 Creative Collaboration Integration Demo Complete!")
print("\\nKey Integration Features Demonstrated:")
print(" ✅ MCP-based autonomous project management")
print(" ✅ Trust-based collaboration invitations")
print(" ✅ Content contribution and versioning")
print(" ✅ Real-time project analytics")
print(" ✅ Personalized project recommendations")
print(" ✅ Complete database persistence")
print("\\n💫 Characters can now autonomously collaborate on creative projects")
print(" using the integrated RAG, MCP, and database systems!")
except Exception as e:
print(f"❌ Demo failed with error: {e}")
import traceback
traceback.print_exc()
async def main():
"""Main demo function"""
demo = CreativeIntegrationDemo()
await demo.run_full_demo()
if __name__ == "__main__":
asyncio.run(main())

View File

@@ -0,0 +1,328 @@
#!/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
# 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.utcnow() - 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.utcnow() - 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.utcnow() - 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.utcnow() - 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.utcnow() - 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())