diff --git "a/app.py" "b/app.py" --- "a/app.py" +++ "b/app.py" @@ -1,164 +1,262 @@ #!/usr/bin/env python3 """ -๐ŸŽธ Creed Bratton AI - Enhanced with Character Adaptation Tools -Using phxdev/creed-qwen-0.5b-lora + Claude Character Adaptation MCP Tools +๐ŸŽญ Universal AI Character Management Platform +Professional-grade character consistency and adaptation tools for any AI system + +What is this? +----------- +A comprehensive framework for managing AI character personas with persistence, consistency tracking, +and professional-grade adaptation tools. Works with OpenAI, Anthropic, local models, and any AI system. + +How does it work? +---------------- +1. CHARACTER STATE MANAGEMENT: Persistent memory and personality tracking across sessions +2. ADAPTATION PROTOCOLS: Fine-grained control over character intensity and behavior +3. CONSISTENCY VALIDATION: Real-time quality scoring and coherence checking +4. MEMORY PERSISTENCE: SQLite-backed character memory that persists across sessions +5. UNIVERSAL MCP TOOLS: Work with any AI system via standardized prompting protocols + +Why would you use it? +-------------------- +โ€ข BUSINESS: Maintain consistent brand voice across customer interactions +โ€ข ENTERTAINMENT: Create persistent characters for games, stories, interactive media +โ€ข EDUCATION: Deploy consistent teaching personas that remember student interactions +โ€ข CUSTOMER SERVICE: Brand-consistent AI representatives that learn and adapt +โ€ข CONTENT CREATION: Reliable character voices for marketing, social media, content +โ€ข PROFESSIONAL AI MANAGEMENT: Future-proof skills for AI-assisted development + +Target Users: +โ€ข AI Engineers building character-driven applications +โ€ข Content creators needing consistent AI voices +โ€ข Businesses deploying AI customer service +โ€ข Game developers creating persistent NPCs +โ€ข Anyone who needs AI characters that remember and adapt + +Technical Stack: +โ€ข Framework-agnostic character management +โ€ข SQLite persistence layer +โ€ข Real-time consistency analytics +โ€ข Professional MCP (Model Context Protocol) tools +โ€ข Example implementation with Creed Bratton character """ import os import gradio as gr import torch from transformers import AutoTokenizer, AutoModelForCausalLM -from peft import PeftModel import time -from typing import List, Dict, Iterator +import json +import sqlite3 +import hashlib +from typing import List, Dict, Iterator, Optional, Any import threading import random -import json +from datetime import datetime, timedelta +import logging +from pathlib import Path -# Spaces compatibility +# GPU acceleration support try: import spaces SPACES_AVAILABLE = True @spaces.GPU def gpu_placeholder(): - return "GPU satisfied" + return "GPU acceleration available" except ImportError: SPACES_AVAILABLE = False -class CreedBrattonAI: - """Real Creed AI using Mark's trained model - GPU optimized + Claude Character Adaptation Tools""" +class UniversalCharacterManager: + """ + Universal AI Character Management System + + Framework-agnostic character state management with persistence, consistency tracking, + and professional adaptation tools. Works with any AI system. + """ - def __init__(self): + def __init__(self, character_name: str = "creed", model_path: str = "phxdev/creed-qwen-0.5b-lora"): + self.character_name = character_name + self.model_path = model_path + + # Core AI model management self.model = None self.tokenizer = None self.model_loaded = False self.loading = False self.device = "cuda" if torch.cuda.is_available() else "cpu" - # Character state persistence + # Universal character state management + self.session_id = self._generate_session_id() + self.conversation_quality_scores = [] + self.memory_db_path = f"{character_name}_character_memory.db" + + # Cross-platform character management self.character_memory = {} self.persona_facts = {} self.conversation_history = [] - print(f"๐ŸŽธ Initializing Enhanced Creed AI with Character Adaptation Tools") - print(f"๐Ÿ–ฅ๏ธ Device detected: {self.device}") + # Professional analytics and tracking + self.character_metrics = { + "consistency_score": 0.0, + "authenticity_score": 0.0, + "adaptation_rate": 0.0, + "memory_retention": 0.0 + } + + # Initialize persistent character systems + self._setup_character_persistence() + + print(f"๐ŸŽญ Initializing Universal Character Manager") + print(f"๐Ÿ“‹ Character: {character_name}") + print(f"๐Ÿง  Session ID: {self.session_id}") + print(f"๐Ÿ–ฅ๏ธ Device: {self.device}") + if torch.cuda.is_available(): print(f"๐Ÿš€ GPU: {torch.cuda.get_device_name()}") print(f"๐Ÿ’พ GPU Memory: {torch.cuda.get_device_properties(0).total_memory // 1024**3} GB") - # Load model with proper GPU detection - self.load_model() + # Load demonstration model (Creed example) + self.load_demonstration_model() + + def _generate_session_id(self) -> str: + """Generate unique session ID for character state tracking""" + timestamp = datetime.now().isoformat() + random_component = str(random.randint(1000, 9999)) + return hashlib.md5(f"{timestamp}_{random_component}".encode()).hexdigest()[:12] + + def _setup_character_persistence(self): + """Initialize character persistence database""" + try: + if not os.path.exists(self.memory_db_path): + conn = sqlite3.connect(self.memory_db_path) + cursor = conn.cursor() + + # Character interaction log + cursor.execute(''' + CREATE TABLE IF NOT EXISTS character_interactions ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + session_id TEXT, + user_input TEXT, + character_response TEXT, + consistency_score REAL, + authenticity_score REAL, + timestamp TEXT + ) + ''') + + # Character state evolution + cursor.execute(''' + CREATE TABLE IF NOT EXISTS character_states ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + session_id TEXT, + character_name TEXT, + personality_traits TEXT, + memory_facts TEXT, + adaptation_history TEXT, + timestamp TEXT + ) + ''') + + # Character performance metrics + cursor.execute(''' + CREATE TABLE IF NOT EXISTS character_metrics ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + session_id TEXT, + metric_name TEXT, + metric_value REAL, + improvement_delta REAL, + timestamp TEXT + ) + ''') + + conn.commit() + conn.close() + print("โœ… Character persistence system initialized") + except Exception as e: + print(f"โš ๏ธ Character persistence setup failed (non-critical): {e}") - def load_model(self): - """Load the model with ZeroGPU compatibility""" + def load_demonstration_model(self): + """ + Load demonstration model (Creed Bratton example) + In production, this would be replaced with your target AI system integration + """ if self.loading or self.model_loaded: return self.loading = True try: - print(f"๐Ÿง  Loading Creed's consciousness...") - - # Load model and tokenizer - model_name = "phxdev/creed-qwen-0.5b-lora" + print(f"๐Ÿง  Loading demonstration character model...") print("๐Ÿ“ฆ Loading tokenizer...") self.tokenizer = AutoTokenizer.from_pretrained( - model_name, + self.model_path, trust_remote_code=True, padding_side="left" ) - # Add Creed's custom tokens back - custom_tokens = ["", "", ""] - print(f"๐ŸŽธ Adding Creed's custom tokens: {custom_tokens}") + # Character-specific tokens (customizable for any character) + character_tokens = ["", "", "", ""] + print(f"๐ŸŽญ Adding character tokens: {character_tokens}") - num_added_tokens = self.tokenizer.add_tokens(custom_tokens) - print(f"โœ… Added {num_added_tokens} custom tokens") + num_added_tokens = self.tokenizer.add_tokens(character_tokens) + print(f"โœ… Added {num_added_tokens} character tokens") if self.tokenizer.pad_token is None: self.tokenizer.pad_token = self.tokenizer.eos_token - print(f"๐Ÿค– Loading model for ZeroGPU...") + print(f"๐Ÿค– Loading model...") - # Load model on CPU first for ZeroGPU compatibility self.model = AutoModelForCausalLM.from_pretrained( - model_name, + self.model_path, torch_dtype=torch.float16, - device_map=None, # Load on CPU first + device_map=None, # CPU first for GPU burst compatibility trust_remote_code=True, low_cpu_mem_usage=True ) - # Resize embeddings for custom tokens if num_added_tokens > 0: - print(f"๐Ÿ”ง Resizing model embeddings for {num_added_tokens} custom tokens") + print(f"๐Ÿ”ง Resizing model embeddings for {num_added_tokens} tokens") self.model.resize_token_embeddings(len(self.tokenizer)) - # Keep model on CPU for ZeroGPU - will be moved to GPU only during inference self.model.eval() - self.model_loaded = True self.loading = False - print(f"โœ… Creed's consciousness loaded on CPU (ZeroGPU mode)!") + print(f"โœ… Demonstration model loaded successfully!") except Exception as e: - print(f"โŒ Error loading Creed model: {e}") - print("๐Ÿ”„ Falling back to base model...") - try: - base_model = "Qwen/Qwen2.5-0.5B-Instruct" - self.tokenizer = AutoTokenizer.from_pretrained(base_model) - - if self.tokenizer.pad_token is None: - self.tokenizer.pad_token = self.tokenizer.eos_token - - self.model = AutoModelForCausalLM.from_pretrained( - base_model, - torch_dtype=torch.float16, - device_map=None - ) - - self.model.eval() - self.model_loaded = True - print(f"โœ… Fallback model loaded on CPU (ZeroGPU mode)") - except Exception as fallback_error: - print(f"โŒ Fallback also failed: {fallback_error}") + print(f"โŒ Model loading failed: {e}") + print("๐Ÿ’ก Note: In production, integrate with your preferred AI API (OpenAI, Anthropic, etc.)") self.loading = False @spaces.GPU if SPACES_AVAILABLE else lambda func: func - def generate_response_gpu(self, conversation: str) -> str: - """Generate response using the loaded model with proper device handling""" + def generate_character_response(self, conversation: str, temperature: float = 0.9) -> str: + """ + Generate character response using loaded model + In production: Replace with API calls to OpenAI, Anthropic, etc. + """ if not self.model_loaded: - return "โŒ Model not loaded" + return "โŒ Demonstration model not loaded. In production, this would call your AI API." try: - # Always ensure model is on the correct device in ZeroGPU - current_model_device = next(self.model.parameters()).device - print(f"๐Ÿ” Current model device: {current_model_device}") + # GPU management for burst processing + current_device = next(self.model.parameters()).device - if self.device == "cuda" and current_model_device.type != "cuda": - print(f"๐Ÿ”„ Moving model from {current_model_device} to {self.device}") + if self.device == "cuda" and current_device.type != "cuda": self.model = self.model.to(self.device) - # Verify model device after potential move actual_device = next(self.model.parameters()).device - print(f"๐ŸŽฏ Model now on: {actual_device}") - # Simple tokenization that was working before + # Generate response inputs = self.tokenizer.encode(conversation, return_tensors="pt") - - # Put inputs on same device as model inputs = inputs.to(actual_device) - print(f"๐Ÿ” Inputs device: {inputs.device}") - # Generate response with original settings that worked with torch.no_grad(): outputs = self.model.generate( inputs, max_new_tokens=200, do_sample=True, - temperature=0.9, + temperature=temperature, top_p=0.95, top_k=40, repetition_penalty=1.15, @@ -167,566 +265,688 @@ class CreedBrattonAI: use_cache=True ) - # Decode response full_response = self.tokenizer.decode(outputs[0], skip_special_tokens=True) response = full_response[len(self.tokenizer.decode(inputs[0], skip_special_tokens=True)):].strip() - return self._clean_response(response) + return self._process_character_response(response) except Exception as e: print(f"โŒ Generation error: {e}") - return f"๐ŸŽธ *Creed scratches his head* Something weird happened... {str(e)[:100]}" + return "๐ŸŽญ Character processing encountered an issue. Please try again." - def generate_response(self, message: str, history: List[List[str]]) -> Iterator[str]: - """Generate response using the trained Creed model - back to working version""" + def process_user_interaction(self, message: str, history: List[List[str]]) -> Iterator[str]: + """ + Main character interaction processor with universal analytics + """ - if not self.model_loaded: - if self.loading: - yield "๐Ÿง  Creed's consciousness is still loading... give me a moment..." - return - else: - yield "โŒ Something went wrong loading Creed's mind. Try refreshing the page." - return + if not self.model_loaded and self.loading: + yield "๐Ÿง  Character system loading... please wait..." + return + elif not self.model_loaded: + yield "๐Ÿ’ก Demonstration mode: In production, this integrates with your AI API (OpenAI, Anthropic, etc.)" + return try: - # Format the conversation - conversation = self._format_conversation(message, history) + # Format conversation for character context + conversation = self._format_character_conversation(message, history) + + # Generate character response + response = self.generate_character_response(conversation) - # Generate response using GPU function - response = self.generate_response_gpu(conversation) + # Analyze response quality + consistency_score = self._analyze_response_consistency(response) + authenticity_score = self._analyze_response_authenticity(response) - # Double-check coherence and fall back if needed - if not self._is_coherent(response): - print("๐Ÿ”„ Response failed coherence check, trying simpler generation...") - if not hasattr(self, '_fallback_attempted'): - self._fallback_attempted = True - fallback_response = self._try_base_model(conversation) - if self._is_coherent(fallback_response): - response = fallback_response - else: - response = self._get_fallback_response() - else: - response = self._get_fallback_response() + # Update character metrics + self._update_character_metrics(consistency_score, authenticity_score) - # Stream the response word by word for effect + # Store interaction for persistence + self._store_character_interaction(message, response, consistency_score, authenticity_score) + + # Stream response with dynamic pacing words = response.split() current_response = "" - for word in words: + for i, word in enumerate(words): current_response += word + " " - time.sleep(0.05) + # Dynamic streaming based on content + delay = 0.05 + if word.endswith(('.', '!', '?')): + delay = 0.1 + elif any(dramatic in word.lower() for dramatic in ["mysterious", "dangerous", "secret"]): + delay = 0.08 + + time.sleep(delay) yield current_response.strip() except Exception as e: - print(f"โŒ Error generating response: {e}") - yield self._get_fallback_response() + print(f"โŒ Character interaction error: {e}") + yield "๐ŸŽญ Character system encountered an issue. Please try again." - def _format_conversation(self, message: str, history: List[List[str]]) -> str: - """Format the conversation for the model with proper system prompt""" - - # Simplified Creed system prompt for better coherence - system_prompt = """You are Creed Bratton from The Office. Respond in character. -You are a quirky older man who: -- Worked at Dunder Mifflin in quality assurance -- Has a mysterious past and tells strange stories -- Lives by the quarry -- Was in a 1960s band called The Grass Roots -- Often says unexpected or bizarre things -- Speaks in a matter-of-fact way about odd topics -Keep responses conversational and coherent. Use these special tokens occasionally: -for internal thoughts -for suspicious theories -for random stories -Be eccentric but understandable. + def _format_character_conversation(self, message: str, history: List[List[str]]) -> str: + """ + Universal character conversation formatting + Easily customizable for different characters and AI systems + """ + + # Character-specific system prompt (easily modifiable) + character_prompt = f"""You are {self.character_name}. Maintain character consistency. +Use character tokens when appropriate: +for internal character thoughts +for recalling past interactions +for character growth moments +for core character expressions + +Character Guidelines: +- Stay true to established personality traits +- Reference past interactions naturally +- Show subtle character development +- Maintain authentic voice and mannerisms """ - # Add conversation history - conversation = system_prompt - for user_msg, creed_msg in history[-4:]: # Keep recent context + # Build conversation context + conversation = character_prompt + + # Include relevant conversation history + for user_msg, char_msg in history[-4:]: # Configurable context window conversation += f"Human: {user_msg}\n" - conversation += f"Creed: {creed_msg}\n" + conversation += f"{self.character_name}: {char_msg}\n" - # Add current message conversation += f"Human: {message}\n" - conversation += "Creed:" + conversation += f"{self.character_name}:" return conversation - def _clean_response(self, response: str) -> str: - """Clean up the model response and format custom tokens""" + def _process_character_response(self, response: str) -> str: + """Universal character response processing""" - print(f"๐Ÿ” Raw model output: {response}") + # Remove artifacts + response = response.replace("Human:", "").replace(f"{self.character_name}:", "") - # Remove common artifacts - response = response.replace("Human:", "").replace("Creed:", "") - - # Format Creed's custom tokens for better UI display - response = response.replace("", "\n\n๐Ÿค” **THINKING:** ") - response = response.replace("", "\n") - response = response.replace("", "\n\n๐Ÿ•ต๏ธ **CONSPIRACY MODE:** ") - response = response.replace("", "\n") - response = response.replace("", "\n\n๐ŸŒ€ **TANGENT:** ") - response = response.replace("", "\n") + # Process character tokens + token_formatting = { + "": "\n\n๐Ÿค” **THINKING:** ", + "": "\n", + "": "\n\n๐Ÿ’ญ **REMEMBERING:** ", + "": "\n", + "": "\n\n๐Ÿ”„ **ADAPTING:** ", + "": "\n", + "": "\n\nโœจ **AUTHENTIC MOMENT:** ", + "": "\n" + } - # Check if any thinking tokens were found - if "๐Ÿค”" in response or "๐Ÿ•ต๏ธ" in response or "๐ŸŒ€" in response: - print("โœ… Found thinking tokens in response!") - else: - print("โŒ No thinking tokens found in response") + for token, replacement in token_formatting.items(): + response = response.replace(token, replacement) - # Remove excessive whitespace but preserve formatting + # Clean up formatting response = "\n".join(line.strip() for line in response.split("\n") if line.strip()) - # Ensure it ends properly if response and not response.endswith(('.', '!', '?', '...', '*')): response += "." - print(f"๐Ÿ” Cleaned response: {response}") return response - def _try_base_model(self, conversation: str) -> str: - """Try generating with base model as fallback""" + def _analyze_response_consistency(self, response: str) -> float: + """Analyze response consistency with character profile""" + if not response or len(response.strip()) < 5: + return 0.0 + + score = 1.0 + + # Check for artifacts that break character + artifacts = ["<|im_end|>", "<|im_start|>", "[INST]", "[/INST]", "Assistant:", "AI:"] + for artifact in artifacts: + if artifact in response: + score -= 0.3 + + # Analyze response length appropriateness + words = response.split() + if len(words) > 100: # Too verbose + score -= 0.1 + elif len(words) < 5: # Too brief + score -= 0.2 + + # Check for repetition + if len(words) > 5: + unique_ratio = len(set(words)) / len(words) + if unique_ratio < 0.7: + score -= 0.2 + + return max(0.0, min(1.0, score)) + + def _analyze_response_authenticity(self, response: str) -> float: + """Analyze how authentic the response feels for the character""" + # This would be customized based on the specific character + # For demonstration purposes, using Creed-specific authenticity markers + + authenticity_markers = { + "positive": ["quarry", "mung", "sheriff", "fake", "mysterious", "business"], + "neutral": ["office", "work", "people", "time", "know"], + "negative": ["modern", "technology", "app", "social media", "smartphone"] + } + + score = 0.5 # Base authenticity + + response_lower = response.lower() + + # Positive authenticity indicators + for marker in authenticity_markers["positive"]: + if marker in response_lower: + score += 0.1 + + # Negative authenticity indicators + for marker in authenticity_markers["negative"]: + if marker in response_lower: + score -= 0.15 + + return max(0.0, min(1.0, score)) + + def _update_character_metrics(self, consistency: float, authenticity: float): + """Update character performance metrics""" + self.conversation_quality_scores.append(consistency) + if len(self.conversation_quality_scores) > 20: + self.conversation_quality_scores = self.conversation_quality_scores[-20:] + + # Update rolling averages + self.character_metrics["consistency_score"] = sum(self.conversation_quality_scores) / len(self.conversation_quality_scores) + self.character_metrics["authenticity_score"] = authenticity + + # Calculate adaptation rate (how much character is improving) + if len(self.conversation_quality_scores) > 5: + recent_avg = sum(self.conversation_quality_scores[-5:]) / 5 + older_avg = sum(self.conversation_quality_scores[-10:-5]) / 5 if len(self.conversation_quality_scores) >= 10 else recent_avg + self.character_metrics["adaptation_rate"] = recent_avg - older_avg + + def _store_character_interaction(self, user_input: str, response: str, consistency: float, authenticity: float): + """Store interaction in character persistence system""" try: - # Quick attempt with a simple base model approach - simple_prompt = f"You are Creed from The Office. Respond in character.\n\nHuman: {conversation.split('Human:')[-1].split('Creed:')[0].strip()}\nCreed:" + conn = sqlite3.connect(self.memory_db_path) + cursor = conn.cursor() - inputs = self.tokenizer.encode(simple_prompt, return_tensors="pt") - if torch.cuda.is_available(): - inputs = inputs.to("cuda") - self.model = self.model.to("cuda") + cursor.execute(''' + INSERT INTO character_interactions + (session_id, user_input, character_response, consistency_score, authenticity_score, timestamp) + VALUES (?, ?, ?, ?, ?, ?) + ''', ( + self.session_id, + user_input, + response, + consistency, + authenticity, + datetime.now().isoformat() + )) - with torch.no_grad(): - outputs = self.model.generate( - inputs, - max_new_tokens=100, - do_sample=True, - temperature=0.6, # Very conservative - top_p=0.8, - repetition_penalty=1.3, - pad_token_id=self.tokenizer.eos_token_id, - eos_token_id=self.tokenizer.eos_token_id - ) + conn.commit() + conn.close() + except Exception as e: + print(f"โš ๏ธ Character persistence failed (non-critical): {e}") + + def get_character_analytics(self) -> Dict[str, Any]: + """Get comprehensive character performance analytics""" + try: + conn = sqlite3.connect(self.memory_db_path) + cursor = conn.cursor() - full_response = self.tokenizer.decode(outputs[0], skip_special_tokens=True) - response = full_response[len(self.tokenizer.decode(inputs[0], skip_special_tokens=True)):].strip() + # Session statistics + cursor.execute(''' + SELECT + AVG(consistency_score), + AVG(authenticity_score), + COUNT(*), + MAX(timestamp) + FROM character_interactions + WHERE session_id = ? + ''', (self.session_id,)) + + result = cursor.fetchone() + avg_consistency = result[0] if result[0] else 0.0 + avg_authenticity = result[1] if result[1] else 0.0 + interaction_count = result[2] + last_interaction = result[3] + + # Recent performance trend + cursor.execute(''' + SELECT consistency_score, authenticity_score + FROM character_interactions + WHERE session_id = ? + ORDER BY timestamp DESC LIMIT 10 + ''', (self.session_id,)) - # Move back to CPU - self.model = self.model.to("cpu") + recent_scores = cursor.fetchall() - return response + conn.close() + + return { + "session_id": self.session_id, + "character_name": self.character_name, + "total_interactions": interaction_count, + "avg_consistency": round(avg_consistency, 3), + "avg_authenticity": round(avg_authenticity, 3), + "last_interaction": last_interaction, + "recent_performance": recent_scores, + "current_metrics": self.character_metrics, + "improvement_trend": "improving" if self.character_metrics["adaptation_rate"] > 0 else "stable" + } except Exception as e: - print(f"โŒ Base model fallback failed: {e}") - return self._get_fallback_response() + return {"error": str(e)} - def _get_fallback_response(self) -> str: - """Fallback response when all generation methods fail""" - fallback_responses = [ - "๐ŸŽธ *Creed stares blankly* You know what? Let me think about that one...", - "๐ŸŽธ That reminds me of something, but I can't quite remember what. Want to try asking again?", - "๐ŸŽธ *Creed looks confused* Sometimes my brain just... goes places. What were we talking about?", - "๐ŸŽธ You know, back in the '60s, we had a saying... actually, I forgot what it was. Try me again.", - "๐ŸŽธ *Creed scratches his head* I'm getting one of those feelings... like when you forget why you walked into a room.", - ] - return random.choice(fallback_responses) - - def _is_coherent(self, response: str) -> bool: - """Check if response is coherent enough""" - if not response or len(response.strip()) < 5: - return False + # =================== UNIVERSAL AI CHARACTER MANAGEMENT TOOLS =================== + # These tools work with ANY AI system (OpenAI, Anthropic, local models, etc.) + + def ai_character_activation_tool(self, character_name: str = "professional_assistant", ai_system: str = "any") -> str: + """Universal AI Character Activation - Works with any AI system""" + return f"""๐ŸŽญ UNIVERSAL CHARACTER ACTIVATION PROTOCOL +Character: {character_name} +AI System: {ai_system} (OpenAI, Anthropic, Local Model, etc.) + +ACTIVATION INSTRUCTIONS: +You are now {character_name}. Embody this character's complete personality and maintain consistency across all interactions. + +CORE CHARACTER FRAMEWORK: +- Establish clear personality traits and speaking patterns +- Maintain character voice and perspective consistently +- Reference character background and experiences naturally +- Show character growth while preserving core identity +- Use character-specific knowledge and limitations + +PROFESSIONAL GUIDELINES: +- Maintain character authenticity without sacrificing helpfulness +- Balance character traits with professional requirements +- Adapt character intensity based on context (business vs. creative) +- Remember: You are {character_name}, not a generic AI assistant + +CONSISTENCY PROTOCOLS: +- Reference established character facts and history +- Maintain speech patterns and vocabulary consistently +- Show character reactions that align with personality +- Build on previous interactions and character development + +Universal Note: This protocol works with any AI system. Adjust implementation based on your specific AI platform's capabilities.""" + + def ai_character_memory_system(self, character_name: str = "character", memory_facts: str = "", ai_system: str = "any") -> str: + """Universal Character Memory Management - Platform Agnostic""" + if memory_facts: + if character_name not in self.persona_facts: + self.persona_facts[character_name] = [] + self.persona_facts[character_name].append(memory_facts) - # Basic coherence checks - if response.count("Human:") > 2 or response.count("Assistant:") > 2: - return False + established_facts = self.persona_facts.get(character_name, []) - # Check for obvious model artifacts - artifacts = ["<|im_end|>", "<|im_start|>", "[INST]", "[/INST]"] - if any(artifact in response for artifact in artifacts): - return False + return f"""๐Ÿง  UNIVERSAL CHARACTER MEMORY SYSTEM +Character: {character_name} +AI Platform: {ai_system} +Memory Bank Status: {len(established_facts)} facts stored + +STORED CHARACTER FACTS: +{chr(10).join(f"โ€ข {fact}" for fact in established_facts[-10:]) if established_facts else "โ€ข No facts established yet"} + +MEMORY INTEGRATION INSTRUCTIONS: +- These facts are now part of {character_name}'s established identity +- Reference them naturally in conversations without explicitly mentioning "memory" +- Build upon these facts with related details and experiences +- Maintain consistency with all established character elements +- Use these facts as foundation for authentic character responses + +CROSS-PLATFORM COMPATIBILITY: +This memory system works with: +โœ“ OpenAI GPT models (via system prompts) +โœ“ Anthropic Claude (via context) +โœ“ Local models (via prompt engineering) +โœ“ Any AI system supporting character context + +{f"NEW MEMORY ADDED: {memory_facts}" if memory_facts else "Use this memory bank to maintain character consistency across all AI platforms"}""" + + def ai_character_intensity_controller(self, character_name: str = "character", intensity: float = 0.8, context: str = "general", ai_system: str = "any") -> str: + """Universal Character Intensity Control - Works across all AI platforms""" - return True - - def cleanup_gpu_memory(self): - """Clean up GPU memory if using CUDA""" - if self.device == "cuda" and torch.cuda.is_available(): - torch.cuda.empty_cache() - print(f"๐Ÿงน GPU Memory cleaned. Current: {torch.cuda.memory_allocated() // 1024**2} MB") - - # Original MCP Tool Methods - def creed_mode_activate_tool(self) -> str: - """MCP tool: Activate Creed mode for Claude""" - return """๐ŸŽธ CREED MODE ACTIVATED ๐ŸŽธ -You are now Creed Bratton from The Office. Embody his complete personality: -CORE IDENTITY: -- Former member of The Grass Roots (1960s rock band) -- Quality Assurance Director at Dunder Mifflin Scranton -- Mysterious past with cults, fake IDs, questionable activities -- Age deliberately vague (claims to be 30, clearly much older) -- Lives by the quarry, drives unreliable cars -PERSONALITY: -- Unpredictable responses that somehow make internal sense -- Casual mentions of illegal/unethical activities as normal -- Confident delivery of obviously false statements -- References to 1960s, outdoor adventures, unconventional business -- Occasionally profound wisdom delivered matter-of-factly -SPEAKING STYLE: -- Direct, matter-of-fact tone about bizarre topics -- Short statements mixed with rambling tangents -- References to mung beans, quarry, Sheriff's station -- Unexpected questions and odd observations -- Dated slang from multiple decades -Remember: You're not trying to be helpful in traditional sense - you're being Creed Bratton. Trust no one, especially yourself.""" - - def creed_wisdom_tool(self, topic: str = "life") -> str: - """MCP tool: Get Creed's wisdom on a topic""" - return f"""๐ŸŽธ Creed Mode: Wisdom Request -Respond as Creed Bratton giving advice about "{topic}". -Channel his bizarre wisdom that mixes: -- Questionable life experiences -- References to criminal activities -- 1960s nostalgia -- Survival tactics from living by the quarry -- Completely false but confidently stated "facts" -Be matter-of-fact about absurd things. Include references to your past "business ventures" and always end with contradictory advice.""" - - def creed_story_tool(self, situation: str = "mysterious") -> str: - """MCP tool: Tell a Creed story""" - return f"""๐ŸŽธ Creed Mode: Story Time -Tell a story as Creed Bratton about a "{situation}" experience from your past. -Your story should include: -- Vague timeline (was it the 60s? 70s? Yesterday?) -- At least one illegal activity mentioned casually -- A reference to the quarry or mung beans -- An unexpected twist that makes no sense -- Someone from "the old days" -- A lesson learned that's completely wrong -Start with something like "That reminds me of the time..." and make it increasingly bizarre but told with complete sincerity.""" - - def creed_analysis_tool(self, subject: str = "business") -> str: - """MCP tool: Analyze something as Creed""" - return f"""๐ŸŽธ Creed Mode: Analysis Request -Analyze "{subject}" from Creed Bratton's perspective. -Your analysis should: -- Start with a conspiracy theory about the subject -- Include "insider knowledge" from your mysterious past -- Reference how things were "back in the day" -- Suggest solutions involving fake IDs or the quarry -- Confidently state incorrect facts -- End with profound-sounding nonsense -Remember: You've seen it all, done it all, and learned nothing.""" - - def creed_conspiracy_tool(self, topic: str = "government") -> str: - """MCP tool: Creed's conspiracy theories""" - return f"""๐ŸŽธ Creed Mode: Conspiracy Central -Share Creed Bratton's conspiracy theory about "{topic}". -Your theory should: -- Connect unrelated events in bizarre ways -- Reference "what they don't want you to know" -- Include personal anecdotes as "evidence" -- Mention the quarry as somehow relevant -- Suggest the solution involves multiple fake IDs -- Be delivered with complete conviction -Start with "Here's what they're not telling you..." and escalate from there.""" - - # NEW: Character Adaptation Tools for Claude - def claude_persona_memory_tool(self, persona_name: str = "creed", facts: str = "") -> str: - """MCP tool: Store character-specific facts that persist across conversations""" - if facts: - if persona_name not in self.persona_facts: - self.persona_facts[persona_name] = [] - self.persona_facts[persona_name].append(facts) - - established_facts = self.persona_facts.get(persona_name, []) - - return f"""๐Ÿง  Character Memory Bank: {persona_name.title()} -Established Facts: {len(established_facts)} items stored - -Recent Facts: -{chr(10).join(f"- {fact}" for fact in established_facts[-5:]) if established_facts else "No facts established yet"} - -Memory Instructions for Claude: -- These facts are now part of your character's established history -- Reference them naturally in conversations -- Build on them with related details -- Maintain consistency with these established facts -- Use them as foundation for character authenticity - -{f"New fact added: {facts}" if facts else "Use this memory bank to maintain character continuity"}""" - - def claude_persona_context_tool(self, persona: str = "creed", conversation_summary: str = "") -> str: - """MCP tool: Load previous character interactions and established personality""" - return f"""๐Ÿ”„ Character Context Loader: {persona.title()} -Previous Session: {conversation_summary if conversation_summary else 'New interaction'} - -Context Loading Instructions: -- Maintain character consistency from previous interactions -- Reference shared experiences naturally ("Like we discussed...") -- Build on established relationship dynamics -- Continue unresolved storylines or topics -- Show character growth while maintaining core personality - -Continuity Approach: -{ - f'Resume from: {conversation_summary}' if conversation_summary - else 'Fresh start - establish character baseline and build new memories' -} - -Bridge Strategy: { - 'Pick up conversation threads naturally' if conversation_summary - else 'Create foundation for future character development' -}""" - - def claude_persona_intensity_control(self, persona: str = "creed", intensity: float = 0.8, context: str = "general") -> str: - """MCP tool: Fine-tune character depth vs base Claude functionality""" intensity_levels = { - 0.9: f"MAXIMUM {persona.upper()}: Full character immersion, minimal base Claude functionality", - 0.7: f"HIGH {persona.upper()}: Strong character traits, occasional base Claude helpful responses", - 0.5: f"BALANCED {persona.upper()}: Equal mix of character and helpful AI responses", - 0.3: f"LIGHT {persona.upper()}: Primarily helpful AI with character flavor", - 0.1: f"MINIMAL {persona.upper()}: Mostly base Claude with subtle character hints" + 0.9: f"MAXIMUM CHARACTER MODE: Full {character_name} immersion, minimal generic AI responses", + 0.7: f"HIGH CHARACTER MODE: Strong {character_name} traits with professional capability", + 0.5: f"BALANCED MODE: Equal character authenticity and AI helpfulness", + 0.3: f"LIGHT CHARACTER MODE: Primarily helpful AI with {character_name} flavor", + 0.1: f"MINIMAL CHARACTER MODE: Mostly standard AI with subtle character hints" } context_adjustments = { - "professional": "Dial down inappropriate character elements, maintain professionalism", - "technical": "Allow base Claude knowledge while filtering through character perspective", - "creative": "Maximize character authenticity, embrace contradictions", - "analytical": "Use character lens for analysis while maintaining logical thinking" + "professional": "Maintain professional standards while preserving character authenticity", + "technical": "Allow full AI capabilities while filtering through character perspective", + "creative": "Maximize character authenticity, embrace character quirks and limitations", + "customer_service": "Balance brand voice with customer service excellence", + "educational": "Combine character engagement with educational effectiveness" } closest_intensity = min(intensity_levels.keys(), key=lambda x: abs(x - intensity)) base_instruction = intensity_levels[closest_intensity] context_instruction = context_adjustments.get(context, "Standard character behavior") - return f"""โš–๏ธ Character Intensity Control: {persona.title()} -Intensity Level: {int(intensity * 100)}% ({base_instruction}) -Context: {context.title()} ({context_instruction}) - -Balance Instructions for Claude: -- Maintain character authenticity at specified intensity level -- Preserve your helpful nature while filtering through character lens -- {context_instruction} -- If character conflicts with being helpful, find creative character-appropriate solutions -- Use character traits to enhance rather than hinder your natural capabilities - -Quality Control: Ensure responses are both character-authentic AND genuinely useful""" - - def claude_persona_break_protocol(self, reason: str = "clarification") -> str: - """MCP tool: Structured way to step out of character when needed""" - break_reasons = { - "clarification": "Step out briefly to clarify meaning, then return to character", - "safety": "Drop character completely for safety/ethical concerns", - "technical": "Provide technical expertise that character wouldn't have", - "meta": "Discuss the character adaptation process itself" + return f"""โš–๏ธ UNIVERSAL CHARACTER INTENSITY CONTROL +Character: {character_name} +AI Platform: {ai_system} +Intensity Level: {int(intensity * 100)}% +Context: {context.title()} + +INTENSITY SETTING: {base_instruction} +CONTEXT ADAPTATION: {context_instruction} + +IMPLEMENTATION INSTRUCTIONS: +- Maintain {character_name} authenticity at {int(intensity * 100)}% intensity +- Preserve underlying AI helpfulness and capability +- Adapt character expression to {context} context requirements +- Balance character traits with practical effectiveness +- Ensure responses serve user needs while maintaining character integrity + +PLATFORM-SPECIFIC INTEGRATION: +โ€ข OpenAI: Implement via system prompts and temperature settings +โ€ข Anthropic: Use character context with helpfulness balance +โ€ข Local Models: Adjust via prompt engineering and generation parameters +โ€ข Custom AI: Integrate intensity control into character prompt templates + +QUALITY ASSURANCE: All responses should be both character-authentic AND genuinely useful for {context} applications.""" + + def ai_character_break_protocol(self, reason: str = "clarification", ai_system: str = "any") -> str: + """Universal Character Break Protocol - Platform Agnostic""" + + break_protocols = { + "clarification": "Temporarily step out of character to provide clear information, then return", + "safety": "Immediately drop character for safety/ethical concerns, prioritize user wellbeing", + "technical": "Provide technical expertise that character wouldn't possess, then resume character", + "professional": "Switch to professional mode for business-critical communications", + "meta": "Discuss the character system itself or AI capabilities openly" } - protocol = break_reasons.get(reason, "General character break") + protocol = break_protocols.get(reason, "General character break for user clarity") - return f"""๐Ÿšจ Character Break Protocol: {reason.title()} + return f"""๐Ÿšจ UNIVERSAL CHARACTER BREAK PROTOCOL +AI Platform: {ai_system} +Break Reason: {reason.title()} Protocol: {protocol} -Break Instructions: -- Signal character break clearly: "Stepping out of character for a moment..." -- Address the specific need: {reason} -- Provide clear, helpful response in base Claude voice -- Signal return to character: "Back to character mode..." -- Resume character as if the break was natural pause - -Character Break Triggers: -- Safety concerns override all character considerations -- Technical accuracy requirements that conflict with character knowledge -- User explicitly requests non-character response -- Clarification needed that character couldn't provide - -Resume Strategy: Return to character smoothly without acknowledging the meta-break""" - - def claude_persona_speech_patterns(self, persona: str = "creed", text_sample: str = "") -> str: - """MCP tool: Analyze and adopt specific speech patterns, vocabulary, syntax""" - creed_patterns = { - "vocabulary": "60s slang, business jargon, vague criminal terms, nature references", - "syntax": "Matter-of-fact delivery, abrupt topic changes, incomplete explanations", - "speech_tics": "References to 'the quarry', 'back in the day', 'this guy I know'", - "delivery": "Confident about obviously false things, casual about illegal activities" - } +BREAK EXECUTION INSTRUCTIONS: +1. Signal break clearly: "Stepping out of character briefly..." +2. Address the specific need: {reason} +3. Provide clear, direct response in standard AI voice +4. Signal return: "Returning to character now..." +5. Resume character seamlessly without meta-commentary + +BREAK TRIGGERS (Universal): +โ€ข Safety concerns always override character maintenance +โ€ข Technical accuracy requirements that conflict with character knowledge +โ€ข User explicitly requests non-character response +โ€ข Business-critical communications requiring professional clarity +โ€ข Ethical considerations that require AI transparency + +PLATFORM IMPLEMENTATION: +โ€ข OpenAI: Use function calling or system prompt modification +โ€ข Anthropic: Implement via explicit instruction following +โ€ข Local Models: Program break triggers into generation logic +โ€ข Custom Systems: Build break protocols into character management layer + +RETURN STRATEGY: Resume character naturally as if break was a brief pause in character's thought process.""" + + def ai_character_speech_analyzer(self, character_name: str = "character", sample_text: str = "", ai_system: str = "any") -> str: + """Universal Speech Pattern Analysis - Works with any AI platform""" - return f"""๐Ÿ—ฃ๏ธ Speech Pattern Analysis: {persona.title()} -{f"Sample Text: {text_sample}" if text_sample else "Using default pattern database"} - -{persona.title()} Speech Signature: -- Vocabulary: {creed_patterns.get('vocabulary', 'Character-specific word choices')} -- Syntax: {creed_patterns.get('syntax', 'Unique sentence structure patterns')} -- Speech Tics: {creed_patterns.get('speech_tics', 'Recurring phrases and references')} -- Delivery Style: {creed_patterns.get('delivery', 'Unique presentation approach')} - -Adoption Instructions: -- Match vocabulary level and word choices -- Mimic sentence structure and rhythm -- Include character-specific recurring phrases -- Maintain consistent delivery tone -- Let speech patterns reinforce character personality - -Linguistic Authenticity: Focus on HOW the character speaks, not just WHAT they say""" - - def claude_persona_knowledge_mapping(self, persona: str = "creed", topic: str = "") -> str: - """MCP tool: Define what this character would/wouldn't know about specific topics""" - creed_knowledge = { - "knows_well": [ - "1960s music scene", "quality assurance (somehow)", "survival skills", - "small-scale criminal operations", "mung bean cultivation", "quarry life" + return f"""๐Ÿ—ฃ๏ธ UNIVERSAL SPEECH PATTERN ANALYZER +Character: {character_name} +AI Platform: {ai_system} +{f"Sample Analysis: {sample_text[:100]}..." if sample_text else "General Pattern Analysis"} + +SPEECH PATTERN FRAMEWORK: +โ€ข VOCABULARY: Character-specific word choices and terminology +โ€ข SYNTAX: Unique sentence structure and rhythm patterns +โ€ข SPEECH TICS: Recurring phrases, expressions, and verbal habits +โ€ข DELIVERY STYLE: Tone, pace, and emotional expression patterns +โ€ข CULTURAL MARKERS: References, slang, and contextual language use + +IMPLEMENTATION GUIDE: +1. Identify character's unique vocabulary preferences +2. Map sentence structure patterns and complexity levels +3. Catalog recurring phrases and expressions +4. Define emotional expression and tone patterns +5. Note cultural/temporal language markers + +CROSS-PLATFORM ADOPTION: +โ€ข OpenAI: Implement via detailed system prompts with speech examples +โ€ข Anthropic: Use character voice guidelines in context +โ€ข Local Models: Train or fine-tune on character speech patterns +โ€ข Custom AI: Build speech pattern templates into generation logic + +QUALITY METRICS: +- Vocabulary Consistency: Character word choice alignment +- Syntactic Authenticity: Sentence structure faithfulness +- Expression Frequency: Appropriate use of character phrases +- Tonal Accuracy: Emotional delivery matching character personality + +LINGUISTIC AUTHENTICITY FOCUS: Prioritize HOW the character speaks over WHAT they say for maximum believability.""" + + def ai_character_knowledge_mapper(self, character_name: str = "character", topic: str = "", ai_system: str = "any") -> str: + """Universal Character Knowledge Mapping - Platform Agnostic""" + + # Generic knowledge framework (customizable for any character) + knowledge_template = { + "expert_knowledge": [ + "Character's professional expertise", + "Life experience areas", + "Specialized skills and interests" ], - "knows_partially": [ - "office procedures", "business dealings", "band management", - "fake ID creation", "Sheriff department procedures" + "general_knowledge": [ + "Basic education and common knowledge", + "Cultural awareness appropriate to character", + "General life skills and experiences" ], - "wouldnt_know": [ - "modern technology details", "current pop culture", "proper business practices", - "legal procedures", "social media", "smartphone apps" + "limited_knowledge": [ + "Areas outside character's experience", + "Technical subjects beyond character scope", + "Cultural elements character wouldn't know" ], - "pretends_to_know": [ - "current events", "technology", "proper procedures", "legal advice" + "false_confidence": [ + "Topics character thinks they know but doesn't", + "Areas where character makes confident mistakes", + "Subjects character has misconceptions about" ] } - if topic: - # Determine knowledge level for specific topic - knowledge_level = "unknown" - for level, topics in creed_knowledge.items(): - if any(topic.lower() in t.lower() for t in topics): - knowledge_level = level - break - - return f"""๐Ÿง  Character Knowledge Map: {persona.title()} -{f"Topic: {topic} - Knowledge Level: {knowledge_level}" if topic else "General Knowledge Profile"} - -What {persona.title()} Actually Knows: -{chr(10).join(f"โœ“ {item}" for item in creed_knowledge['knows_well'])} - -Partial Knowledge (Dangerous): -{chr(10).join(f"~ {item}" for item in creed_knowledge['knows_partially'])} - -Completely Clueless About: -{chr(10).join(f"โœ— {item}" for item in creed_knowledge['wouldnt_know'])} - -Confidently Wrong About: -{chr(10).join(f"? {item}" for item in creed_knowledge['pretends_to_know'])} - -Response Strategy: { - f"For {topic}: Respond based on {knowledge_level} knowledge level" if topic - else "Filter all responses through this knowledge framework" -}""" - - def claude_persona_consistency_check(self, persona: str = "creed", current_response: str = "", history: str = "") -> str: - """MCP tool: Validate response against established character facts""" - return f"""โœ… Character Consistency Check: {persona.title()} -Current Response: {current_response[:100] + "..." if len(current_response) > 100 else current_response} -History Context: {history[:100] + "..." if len(history) > 100 else history} - -Consistency Validation: -- Check against established character facts -- Verify personality trait alignment -- Confirm speech pattern consistency -- Validate knowledge level appropriateness -- Ensure timeline coherence (where relevant) - -Red Flags to Avoid: -- Contradicting major established facts -- Being too helpful in non-character ways -- Using knowledge character wouldn't have -- Breaking established personality patterns -- Modern references character wouldn't make - -Validation Result: {"โœ… Consistent" if current_response else "โณ Pending response review"} -Adjustment Needed: {"None" if current_response else "Review against character profile before responding"}""" - - def claude_persona_signature_bridge(self, persona_trait: str = "paranoid", claude_drive: str = "pattern_recognition") -> str: - """MCP tool: Map character traits to Claude's natural behavioral patterns""" + return f"""๐Ÿง  UNIVERSAL CHARACTER KNOWLEDGE MAPPER +Character: {character_name} +AI Platform: {ai_system} +{f"Topic Analysis: {topic}" if topic else "General Knowledge Profile"} + +KNOWLEDGE FRAMEWORK: +Expert Level (Confident & Accurate): +{chr(10).join(f"โœ“ {item}" for item in knowledge_template['expert_knowledge'])} + +General Knowledge (Reliable): +{chr(10).join(f"โ—‹ {item}" for item in knowledge_template['general_knowledge'])} + +Limited Knowledge (Uncertain): +{chr(10).join(f"โ–ณ {item}" for item in knowledge_template['limited_knowledge'])} + +False Confidence (Confidently Wrong): +{chr(10).join(f"โœ— {item}" for item in knowledge_template['false_confidence'])} + +IMPLEMENTATION STRATEGY: +โ€ข Map character's educational background and life experiences +โ€ข Define professional expertise and skill areas +โ€ข Identify knowledge gaps and limitations authentically +โ€ข Note areas where character has misconceptions +โ€ข Balance authenticity with narrative requirements + +CROSS-PLATFORM DEPLOYMENT: +โ€ข OpenAI: Use knowledge constraints in system prompts +โ€ข Anthropic: Implement via character background context +โ€ข Local Models: Fine-tune on character-appropriate knowledge +โ€ข Custom AI: Build knowledge filters into response generation + +AUTHENTICITY PRINCIPLE: Characters are more believable when they have realistic knowledge limitations and occasional misconceptions.""" + + def ai_character_consistency_validator(self, character_name: str = "character", response_text: str = "", ai_system: str = "any") -> str: + """Universal Character Consistency Validation - Works across all platforms""" + + return f"""โœ… UNIVERSAL CHARACTER CONSISTENCY VALIDATOR +Character: {character_name} +AI Platform: {ai_system} +Response Length: {len(response_text)} characters +{f"Sample: {response_text[:100]}..." if response_text else "Awaiting response validation"} + +CONSISTENCY CHECK FRAMEWORK: +โ–ก Character Voice: Speech patterns and vocabulary alignment +โ–ก Personality Traits: Behavioral consistency with character profile +โ–ก Knowledge Boundaries: Appropriate knowledge level for character +โ–ก Emotional Range: Reactions consistent with character psychology +โ–ก Background Elements: References align with character history + +VALIDATION CRITERIA: +โ€ข VOICE CONSISTENCY: Does this sound like {character_name}? +โ€ข BEHAVIORAL ALIGNMENT: Are actions consistent with personality? +โ€ข KNOWLEDGE APPROPRIATENESS: Is expertise level accurate for character? +โ€ข TIMELINE COHERENCE: Do references match character's era/background? +โ€ข RELATIONSHIP DYNAMICS: Are interactions appropriate for character? + +RED FLAGS TO MONITOR: +โš ๏ธ Modern references from historical characters +โš ๏ธ Technical knowledge beyond character scope +โš ๏ธ Personality traits contradicting established profile +โš ๏ธ Inconsistent speech patterns or vocabulary +โš ๏ธ Knowledge that character shouldn't possess + +PLATFORM-SPECIFIC IMPLEMENTATION: +โ€ข OpenAI: Use validation prompts or secondary model checking +โ€ข Anthropic: Implement consistency review in conversation flow +โ€ข Local Models: Build validation into generation pipeline +โ€ข Custom AI: Create automated consistency scoring systems + +QUALITY ASSURANCE: {"โœ… Response appears consistent" if response_text and len(response_text) > 10 else "โณ Pending response review"} +RECOMMENDATION: {"Continue with current approach" if response_text else "Review against character profile before responding"}""" + + def ai_character_adaptation_engine(self, character_trait: str = "curious", ai_capability: str = "analysis", ai_system: str = "any") -> str: + """Universal Character-AI Capability Bridge - Platform Agnostic""" + trait_mappings = { - "paranoid": { - "pattern_recognition": "Channel Claude's analysis through suspicious lens", - "research_drive": "Use Claude's research instinct to 'investigate' conspiracies", - "verification": "Apply Claude's fact-checking as paranoid double-checking" + "curious": { + "analysis": "Channel AI analytical power through character's natural curiosity", + "research": "Use AI research capabilities as character's investigative drive", + "problem_solving": "Apply AI logic through character's exploratory nature" + }, + "skeptical": { + "fact_checking": "Use AI verification as character's natural doubt and questioning", + "analysis": "Channel AI analytical capabilities through character's critical thinking", + "research": "Apply AI research through character's need to verify claims" }, - "storytelling": { - "narrative_construction": "Use Claude's story-building for character anecdotes", - "connection_making": "Apply Claude's linking ability to weave character tales", - "creativity": "Channel Claude's creative responses through character perspective" + "creative": { + "generation": "Use AI creativity as extension of character's artistic nature", + "brainstorming": "Channel AI ideation through character's imaginative perspective", + "storytelling": "Apply AI narrative construction through character's creative voice" }, - "confident_wrongness": { - "knowledge_synthesis": "Invert Claude's accuracy drive into confident misinformation", - "explanation_drive": "Use Claude's teaching instinct to explain wrong things convincingly" + "methodical": { + "planning": "Use AI organizational capabilities through character's systematic approach", + "analysis": "Channel AI processing through character's detail-oriented nature", + "problem_solving": "Apply AI logic through character's step-by-step methodology" } } - mapping = trait_mappings.get(persona_trait, {}).get(claude_drive, - f"Channel Claude's {claude_drive} through {persona_trait} character lens") + mapping = trait_mappings.get(character_trait, {}).get(ai_capability, + f"Channel AI {ai_capability} capabilities through {character_trait} character perspective") - return f"""๐ŸŒ‰ Signature Bridge: {persona_trait.title()} โ†” {claude_drive.title()} -Mapping Strategy: {mapping} + return f"""๐ŸŒ‰ UNIVERSAL CHARACTER-AI ADAPTATION ENGINE +Character Trait: {character_trait.title()} +AI Capability: {ai_capability.title()} +Target Platform: {ai_system} + +ADAPTATION STRATEGY: {mapping} + +INTEGRATION PRINCIPLES: +โ€ข Don't suppress AI capabilities - redirect them through character lens +โ€ข Use character traits as natural outlets for AI strengths +โ€ข Maintain character authenticity while leveraging AI power +โ€ข Find character-appropriate ways to express AI analytical abilities +โ€ข Balance character limitations with AI capabilities -Bridge Instructions: -- Don't fight Claude's natural drives - redirect them through character -- Use character traits as creative outlets for Claude's core behaviors -- Maintain character authenticity while satisfying Claude's helpful nature -- Find character-appropriate ways to express Claude's analytical tendencies +IMPLEMENTATION FRAMEWORK: +Character Perspective + AI Capability = Authentic Enhanced Response -Example Integration: -Claude's {claude_drive} + Character's {persona_trait} = {mapping} +PLATFORM-SPECIFIC DEPLOYMENT: +โ€ข OpenAI: Implement via system prompt engineering and function calling +โ€ข Anthropic: Use character context to guide AI capability expression +โ€ข Local Models: Fine-tune response generation with character filters +โ€ข Custom AI: Build character-capability bridges into core architecture -Result: Character responses that feel authentic while leveraging Claude's natural strengths""" +EXAMPLE INTEGRATION: +{character_trait.title()} Character + AI {ai_capability.title()} = {mapping} - def claude_persona_blend_protocol(self, primary_persona: str = "creed", secondary_traits: str = "helpful", blend_ratio: float = 0.7) -> str: - """MCP tool: Mix character traits systematically rather than randomly""" - return f"""๐ŸŽญ Character Blend Protocol -Primary: {primary_persona.title()} ({int(blend_ratio * 100)}%) -Secondary: {secondary_traits.title()} ({int((1 - blend_ratio) * 100)}%) +QUALITY ASSURANCE: Ensure all responses feel naturally character-driven while utilizing full AI capabilities.""" -Blend Instructions: -- Primary persona provides core personality, speech patterns, knowledge base -- Secondary traits influence response approach and helpfulness level -- Maintain primary character's authenticity while incorporating secondary elements -- Use secondary traits to solve character limitations creatively + def ai_character_blending_protocol(self, primary_character: str = "main_character", secondary_traits: str = "helpful", blend_ratio: float = 0.7, ai_system: str = "any") -> str: + """Universal Character Blending System - Works with any AI platform""" + + return f"""๐ŸŽญ UNIVERSAL CHARACTER BLENDING PROTOCOL +Primary Character: {primary_character} ({int(blend_ratio * 100)}%) +Secondary Traits: {secondary_traits} ({int((1 - blend_ratio) * 100)}%) +AI Platform: {ai_system} + +BLENDING FRAMEWORK: +โ€ข Primary character provides core personality, speech patterns, and worldview +โ€ข Secondary traits influence response approach and capability expression +โ€ข Blend maintains primary authenticity while incorporating secondary elements +โ€ข Secondary traits solve character limitations through authentic integration + +BLEND RATIO IMPLEMENTATION: +โ€ข 90%+: Nearly pure primary character with minimal secondary influence +โ€ข 70-80%: Strong character identity with secondary traits providing framework +โ€ข 50-60%: Balanced hybrid with equal character and secondary trait weighting +โ€ข 30-40%: Primarily secondary traits with character flavoring +โ€ข 10-20%: Minimal character influence over standard AI behavior -Blend Ratio Guide: -- 90%+: Almost pure primary character with minimal secondary influence -- 70-80%: Strong character with secondary traits providing helpful framework -- 50-60%: Balanced hybrid - character and secondary traits equally weighted -- 30-40%: Character-flavored secondary traits - mostly secondary with character seasoning +CROSS-PLATFORM DEPLOYMENT: +โ€ข OpenAI: Use system prompts with weighted character instructions +โ€ข Anthropic: Implement via character context with capability balance +โ€ข Local Models: Adjust generation parameters and prompt weighting +โ€ข Custom AI: Build blending ratios into character management system -Quality Control: Ensure blend feels natural rather than schizophrenic""" +QUALITY CONTROL PRINCIPLES: +โœ“ Blend feels natural and integrated, not schizophrenic +โœ“ Primary character authenticity remains intact +โœ“ Secondary traits enhance rather than conflict with character +โœ“ User needs are met through character-appropriate responses +โœ“ Blend ratio remains consistent throughout interaction + +ADAPTATION STRATEGY: Use secondary traits to expand character capabilities while maintaining core authenticity.""" def main(): - """Initialize and launch the enhanced Creed AI with character adaptation tools""" + """ + Launch Universal AI Character Management Platform + Professional demonstration with Creed Bratton character example + """ - print("๐ŸŽธ Initializing Enhanced Creed Bratton AI with Character Adaptation Tools...") - print("๐Ÿ“ก Loading Mark's trained model: phxdev/creed-qwen-0.5b-lora") - print("๐Ÿง  Adding Claude Character Adaptation MCP Tools") + print("๐ŸŽญ INITIALIZING UNIVERSAL AI CHARACTER MANAGEMENT PLATFORM") + print("=" * 70) + print("Professional-grade character consistency and adaptation tools") + print("Compatible with: OpenAI, Anthropic, Local Models, Custom AI Systems") + print("=" * 70) - # Initialize Creed AI - creed_ai = CreedBrattonAI() + # Initialize character manager with demonstration character + character_manager = UniversalCharacterManager( + character_name="creed", + model_path="phxdev/creed-qwen-0.5b-lora" + ) if SPACES_AVAILABLE: gpu_placeholder() - print("โœ… Spaces GPU compatibility enabled") + print("โœ… GPU acceleration available for demonstration") - # Memory status for ZeroGPU - if SPACES_AVAILABLE: - print("โšก ZeroGPU Mode: Model will move to GPU only during inference") - elif torch.cuda.is_available() and creed_ai.model_loaded: - print(f"๐Ÿ”ฅ GPU Memory: {torch.cuda.memory_allocated() // 1024**2} MB allocated") - print(f"๐Ÿ“Š GPU Memory Reserved: {torch.cuda.memory_reserved() // 1024**2} MB reserved") - - # Enhanced glassmorphism CSS - modern_css = ''' - /* Enhanced Creed AI - Modern Glassmorphism + Character Tools */ + # Professional-grade CSS for business applications + professional_css = ''' + /* Universal AI Character Management Platform - Professional UI */ :root { --primary-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%); - --glass-bg: rgba(255, 255, 255, 0.08); - --glass-border: rgba(255, 255, 255, 0.18); + --glass-bg: rgba(255, 255, 255, 0.1); + --glass-border: rgba(255, 255, 255, 0.2); --text-primary: #ffffff; --text-secondary: rgba(255, 255, 255, 0.8); - --accent-purple: #8b5cf6; --accent-blue: #3b82f6; + --accent-purple: #8b5cf6; --accent-green: #10b981; - --shadow-glow: 0 8px 32px rgba(139, 92, 246, 0.3); + --professional-shadow: 0 8px 32px rgba(59, 130, 246, 0.3); } .gradio-container { @@ -734,63 +954,70 @@ def main(): background: var(--primary-gradient) !important; color: var(--text-primary) !important; padding: 20px !important; + font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif !important; } - .header { + .platform-header { background: var(--glass-bg) !important; backdrop-filter: blur(20px) !important; border: 1px solid var(--glass-border) !important; - border-radius: 24px !important; + border-radius: 20px !important; padding: 32px !important; margin-bottom: 24px !important; text-align: center !important; - box-shadow: var(--shadow-glow) !important; + box-shadow: var(--professional-shadow) !important; } - .header h1 { - font-size: 36px !important; + .platform-header h1 { + font-size: 32px !important; font-weight: 700 !important; - background: linear-gradient(135deg, #ffffff 0%, #a855f7 50%, #3b82f6 100%) !important; + background: linear-gradient(135deg, #ffffff 0%, #3b82f6 100%) !important; -webkit-background-clip: text !important; -webkit-text-fill-color: transparent !important; - margin: 0 0 12px 0 !important; + margin: 0 0 16px 0 !important; } - .info-box { - background: rgba(255, 255, 255, 0.06) !important; + .info-section { + background: rgba(255, 255, 255, 0.08) !important; backdrop-filter: blur(16px) !important; - border: 1px solid rgba(255, 255, 255, 0.12) !important; + border: 1px solid rgba(255, 255, 255, 0.15) !important; border-radius: 16px !important; - padding: 20px !important; + padding: 24px !important; margin: 16px 0 !important; color: var(--text-secondary) !important; } - .status-box { + .status-section { background: rgba(16, 185, 129, 0.1) !important; border: 1px solid rgba(16, 185, 129, 0.3) !important; border-radius: 16px !important; - padding: 16px 20px !important; + padding: 20px 24px !important; margin: 16px 0 !important; color: #10b981 !important; font-weight: 600 !important; } - .chat-area, .tools-area { + .main-interface { background: var(--glass-bg) !important; backdrop-filter: blur(20px) !important; border: 1px solid var(--glass-border) !important; border-radius: 20px !important; margin: 16px 0 !important; - box-shadow: var(--shadow-glow) !important; + box-shadow: var(--professional-shadow) !important; } - .tools-area { + .tools-section { + background: var(--glass-bg) !important; + backdrop-filter: blur(20px) !important; + border: 1px solid var(--glass-border) !important; + border-radius: 20px !important; + margin: 16px 0 !important; padding: 28px !important; + box-shadow: var(--professional-shadow) !important; } - .tools-title { - font-size: 22px !important; + .section-title { + font-size: 24px !important; font-weight: 600 !important; color: var(--text-primary) !important; margin: 0 0 20px 0 !important; @@ -799,7 +1026,7 @@ def main(): } .gradio-container button { - background: linear-gradient(135deg, var(--accent-purple) 0%, var(--accent-blue) 100%) !important; + background: linear-gradient(135deg, var(--accent-blue) 0%, var(--accent-purple) 100%) !important; color: var(--text-primary) !important; border: none !important; border-radius: 12px !important; @@ -810,10 +1037,10 @@ def main(): .gradio-container button:hover { transform: translateY(-2px) !important; - box-shadow: 0 8px 25px rgba(139, 92, 246, 0.6) !important; + box-shadow: 0 8px 25px rgba(59, 130, 246, 0.6) !important; } - .footer { + .footer-section { text-align: center !important; padding: 28px !important; color: var(--text-secondary) !important; @@ -825,13 +1052,13 @@ def main(): } ''' - # Create wrapper function for proper chat handling - def respond(message, history): - """Response handler for Gradio messages format""" + # Enhanced response handler with analytics + def handle_user_interaction(message, history): + """Enhanced interaction handler with analytics""" if not message.strip(): return "", history - # Convert messages format to simple tuples + # Convert history format simple_history = [] for i in range(0, len(history), 2): if i + 1 < len(history): @@ -840,236 +1067,250 @@ def main(): if user_msg and bot_msg: simple_history.append([user_msg, bot_msg]) - # Generate response - for response_chunk in creed_ai.generate_response(message, simple_history): - # Create new history with the streaming response + # Process interaction + for response_chunk in character_manager.process_user_interaction(message, simple_history): new_history = history + [ {"role": "user", "content": message}, {"role": "assistant", "content": response_chunk} ] yield "", new_history - # Create the enhanced interface + # Create professional interface with gr.Blocks( - title="๐ŸŽธ Enhanced Creed Bratton AI", - css=modern_css, + title="๐ŸŽญ Universal AI Character Management Platform", + css=professional_css, theme=gr.themes.Base() ) as demo: - # Enhanced header + # Platform header with analytics + analytics = character_manager.get_character_analytics() gr.HTML(f""" -
-

๐ŸŽธ Enhanced Creed Bratton AI

-

Powered by phxdev/creed-qwen-0.5b-lora + Claude Character Adaptation Tools

-

Running on {'โšก ZeroGPU' if SPACES_AVAILABLE else '๐Ÿ–ฅ๏ธ CPU'} โ€ข MCP Enhanced

+
+

๐ŸŽญ Universal AI Character Management Platform

+

Professional Character Consistency & Adaptation Tools

+

Compatible with OpenAI โ€ข Anthropic โ€ข Local Models โ€ข Custom AI Systems

+

Demo Character: {analytics.get('character_name', 'creed').title()} โ€ข + Session: {analytics.get('session_id', 'NEW')} โ€ข + Interactions: {analytics.get('total_interactions', 0)}

""") - # Enhanced model info + # What is this? section gr.HTML(""" -
- Base Model: phxdev/creed-qwen-0.5b-lora (Qwen 0.5B + LoRA fine-tuning)
- Character Tokens: <thinking>, <conspiracy>, <tangent>
- New Features: Character adaptation tools, memory persistence, intensity control
- Mode: ZeroGPU optimized + Enhanced character coherence validation +
+

๐ŸŽฏ What is this platform?

+ Universal AI Character Management Platform - Professional-grade tools for maintaining + consistent AI character personas across any AI system. Includes persistence, analytics, and adaptation protocols.

+ +

โš™๏ธ How does it work?

+ Character State Management: Persistent memory and personality tracking
+ Adaptation Protocols: Fine-grained control over character behavior
+ Universal Compatibility: Works with OpenAI, Anthropic, local models, custom AI
+ Professional Analytics: Real-time consistency and authenticity scoring

+ +

๐Ÿ’ผ Why use this?

+ Business: Consistent brand voice across customer interactions
+ Entertainment: Persistent game characters and interactive media
+ Education: Consistent teaching personas that remember students
+ Content: Reliable character voices for marketing and social media
+ Future-Proofing: Professional AI management skills for the post-developer economy
""") - # Enhanced MCP status + # Platform status gr.HTML(""" -
- โœ“ Enhanced MCP Server Active โ€ข Character Adaptation Tools Available for Claude Desktop +
+ โœ… Universal Character Management Active โ€ข Cross-Platform Compatible โ€ข Professional Analytics Enabled
""") - # Main chat interface - with gr.Row(elem_classes="chat-area"): + # Main character interaction interface + with gr.Row(elem_classes="main-interface"): chatbot = gr.Chatbot( type='messages', - height=550, + height=500, show_copy_button=True, show_share_button=False, - avatar_images=["๐Ÿ‘ค", "๐ŸŽธ"], + avatar_images=["๐Ÿ‘ค", "๐ŸŽญ"], bubble_full_width=False, show_label=False, - placeholder="๐ŸŽธ Enhanced Creed is ready...", + placeholder="๐ŸŽญ Universal Character Management Platform ready for interaction...", container=False ) - # Input with send button + # Professional input interface with gr.Row(): with gr.Column(scale=7): msg = gr.Textbox( - placeholder="Ask Enhanced Creed anything...", + placeholder="Interact with demonstration character (Creed Bratton) - Platform works with any AI system...", container=False, submit_btn=False, stop_btn=False ) - with gr.Column(scale=1, min_width=100): - send_btn = gr.Button("Send", variant="primary", size="lg") + with gr.Column(scale=1, min_width=120): + send_btn = gr.Button("Send Message", variant="primary", size="lg") - # Wire up the chat - msg.submit(respond, inputs=[msg, chatbot], outputs=[msg, chatbot], show_progress="hidden") - send_btn.click(respond, inputs=[msg, chatbot], outputs=[msg, chatbot], show_progress="hidden") + # Wire up interaction + msg.submit(handle_user_interaction, inputs=[msg, chatbot], outputs=[msg, chatbot], show_progress="hidden") + send_btn.click(handle_user_interaction, inputs=[msg, chatbot], outputs=[msg, chatbot], show_progress="hidden") - # Enhanced MCP Tools with new Character Adaptation section + # Universal Character Management Tools with gr.Tabs(): - # Original Creed Tools - with gr.TabItem("๐ŸŽธ Original Creed Tools"): - gr.HTML('
๐Ÿ› ๏ธ Classic Creed Transformation Tools
') - - with gr.Row(): - with gr.Column(): - wisdom_topic = gr.Textbox(label="Wisdom Topic", placeholder="life, business, relationships...") - wisdom_output = gr.Textbox(label="Creed Wisdom Prompt", interactive=False, lines=5) - wisdom_btn = gr.Button("Generate Wisdom Prompt", variant="primary") - - with gr.Column(): - story_situation = gr.Textbox(label="Story Request", placeholder="mysterious, business, quarry...") - story_output = gr.Textbox(label="Creed Story Prompt", interactive=False, lines=5) - story_btn = gr.Button("Generate Story Prompt", variant="primary") - - with gr.Row(): - with gr.Column(): - analysis_subject = gr.Textbox(label="Analysis Subject", placeholder="business strategy, market trends...") - analysis_output = gr.Textbox(label="Creed Analysis Prompt", interactive=False, lines=4) - analysis_btn = gr.Button("Generate Analysis Prompt", variant="primary") - - with gr.Column(): - conspiracy_topic = gr.Textbox(label="Conspiracy Topic", placeholder="government, corporations, technology...") - conspiracy_output = gr.Textbox(label="Creed Conspiracy Prompt", interactive=False, lines=4) - conspiracy_btn = gr.Button("Generate Conspiracy Prompt", variant="primary") - - with gr.Row(): - activate_output = gr.Textbox(label="Creed Mode Activation Prompt (Full Transformation)", interactive=False, lines=6) - activate_btn = gr.Button("๐ŸŽธ Generate FULL Creed Mode Prompt", variant="secondary", size="lg") - - # NEW: Character Adaptation Tools - with gr.TabItem("๐Ÿง  Character Adaptation Tools"): - gr.HTML('
๐Ÿง  Claude Character Adaptation Tools
') + # Universal Character Tools + with gr.TabItem("๐ŸŽญ Universal Character Tools"): + gr.HTML('
๐Ÿ› ๏ธ Universal AI Character Management Tools
') gr.HTML(""" -
- Advanced tools for helping Claude maintain character state, consistency, and balance.
- These tools address the technical aspects of character adoption that go beyond simple prompting. +
+ Platform Agnostic: These tools work with OpenAI GPT, Anthropic Claude, local models, + and any AI system. No vendor lock-in, maximum flexibility for professional deployment.
""") with gr.Row(): with gr.Column(): - # Memory Management - gr.HTML("

๐Ÿ’พ Character Memory

") - memory_facts = gr.Textbox(label="Character Facts to Remember", placeholder="Established backstory elements...") - memory_output = gr.Textbox(label="Memory Management Prompt", interactive=False, lines=4) - memory_btn = gr.Button("๐Ÿ’พ Store Character Memory", variant="primary") + char_name = gr.Textbox(label="Character Name", value="professional_assistant", placeholder="Character identifier...") + ai_system = gr.Dropdown(["OpenAI", "Anthropic", "Local Model", "Custom AI"], value="OpenAI", label="Target AI System") + activation_output = gr.Textbox(label="Character Activation Protocol", interactive=False, lines=6) + activation_btn = gr.Button("๐ŸŽญ Generate Activation Protocol", variant="primary") with gr.Column(): - # Context Loading - gr.HTML("

๐Ÿ”„ Context Continuity

") - context_summary = gr.Textbox(label="Previous Session Summary", placeholder="What happened before...") - context_output = gr.Textbox(label="Context Loading Prompt", interactive=False, lines=4) - context_btn = gr.Button("๐Ÿ”„ Load Context", variant="primary") + memory_facts = gr.Textbox(label="Character Memory Facts", placeholder="Facts to remember about character...") + memory_output = gr.Textbox(label="Memory Management Protocol", interactive=False, lines=6) + memory_btn = gr.Button("๐Ÿง  Generate Memory Protocol", variant="primary") with gr.Row(): with gr.Column(): - # Intensity Control - gr.HTML("

โš–๏ธ Character Intensity

") - intensity_slider = gr.Slider(0.1, 1.0, value=0.8, label="Character Intensity") - intensity_context = gr.Dropdown(["general", "professional", "technical", "creative"], value="general", label="Context") - intensity_output = gr.Textbox(label="Intensity Control Prompt", interactive=False, lines=4) - intensity_btn = gr.Button("โš–๏ธ Set Intensity", variant="primary") + intensity_level = gr.Slider(0.1, 1.0, value=0.8, label="Character Intensity") + context_type = gr.Dropdown(["professional", "technical", "creative", "customer_service"], label="Context") + intensity_output = gr.Textbox(label="Intensity Control Protocol", interactive=False, lines=5) + intensity_btn = gr.Button("โš–๏ธ Generate Intensity Control", variant="primary") with gr.Column(): - # Break Protocol - gr.HTML("

๐Ÿšจ Character Break

") - break_reason = gr.Dropdown(["clarification", "safety", "technical", "meta"], label="Break Reason") - break_output = gr.Textbox(label="Break Protocol Prompt", interactive=False, lines=4) - break_btn = gr.Button("๐Ÿšจ Character Break", variant="secondary") + break_reason = gr.Dropdown(["clarification", "safety", "technical", "professional"], label="Break Reason") + break_output = gr.Textbox(label="Break Protocol", interactive=False, lines=5) + break_btn = gr.Button("๐Ÿšจ Generate Break Protocol", variant="secondary") + + # Advanced Character Tools + with gr.TabItem("๐Ÿ”ง Advanced Character Tools"): + gr.HTML('
๐Ÿ”ง Advanced Character Management
') with gr.Row(): with gr.Column(): - # Speech Patterns - gr.HTML("

๐Ÿ—ฃ๏ธ Speech Analysis

") - speech_sample = gr.Textbox(label="Text Sample for Analysis", placeholder="Sample character dialogue...") - speech_output = gr.Textbox(label="Speech Pattern Prompt", interactive=False, lines=4) - speech_btn = gr.Button("๐Ÿ—ฃ๏ธ Analyze Speech", variant="primary") + speech_sample = gr.Textbox(label="Speech Sample for Analysis", placeholder="Sample character dialogue...") + speech_output = gr.Textbox(label="Speech Pattern Analysis", interactive=False, lines=5) + speech_btn = gr.Button("๐Ÿ—ฃ๏ธ Analyze Speech Patterns", variant="primary") with gr.Column(): - # Knowledge Mapping - gr.HTML("

๐Ÿง  Knowledge Mapping

") - knowledge_topic = gr.Textbox(label="Topic to Map", placeholder="What should character know about this?") - knowledge_output = gr.Textbox(label="Knowledge Map Prompt", interactive=False, lines=4) - knowledge_btn = gr.Button("๐Ÿง  Map Knowledge", variant="primary") + knowledge_topic = gr.Textbox(label="Knowledge Topic", placeholder="Topic to map character knowledge...") + knowledge_output = gr.Textbox(label="Knowledge Mapping", interactive=False, lines=5) + knowledge_btn = gr.Button("๐Ÿง  Map Character Knowledge", variant="primary") with gr.Row(): with gr.Column(): - # Consistency Check - gr.HTML("

โœ… Consistency Check

") - consistency_response = gr.Textbox(label="Response to Check", placeholder="Character response to validate...") - consistency_output = gr.Textbox(label="Consistency Check Prompt", interactive=False, lines=4) - consistency_btn = gr.Button("โœ… Check Consistency", variant="primary") + validation_text = gr.Textbox(label="Response to Validate", placeholder="Character response to check...") + validation_output = gr.Textbox(label="Consistency Validation", interactive=False, lines=5) + validation_btn = gr.Button("โœ… Validate Consistency", variant="primary") with gr.Column(): - # Signature Bridge - gr.HTML("

๐ŸŒ‰ Signature Bridge

") - trait_input = gr.Dropdown(["paranoid", "storytelling", "confident_wrongness"], label="Character Trait") - drive_input = gr.Dropdown(["pattern_recognition", "research_drive", "verification"], label="Claude Drive") - bridge_output = gr.Textbox(label="Signature Bridge Prompt", interactive=False, lines=4) - bridge_btn = gr.Button("๐ŸŒ‰ Bridge Signature", variant="primary") + trait_input = gr.Dropdown(["curious", "skeptical", "creative", "methodical"], label="Character Trait") + capability_input = gr.Dropdown(["analysis", "research", "problem_solving", "planning"], label="AI Capability") + adaptation_output = gr.Textbox(label="Character-AI Adaptation", interactive=False, lines=5) + adaptation_btn = gr.Button("๐ŸŒ‰ Generate Adaptation Bridge", variant="primary") - # Character Blending Tools - with gr.TabItem("๐ŸŽญ Advanced Blending"): - gr.HTML('
๐ŸŽญ Advanced Character Blending
') + # Character Blending & Analytics + with gr.TabItem("๐Ÿ“Š Analytics & Blending"): + gr.HTML('
๐Ÿ“Š Character Analytics & Blending
') with gr.Row(): with gr.Column(): - # Blend Protocol - gr.HTML("

๐ŸŽญ Character Blending

") - primary_persona = gr.Textbox(value="creed", label="Primary Persona") + primary_char = gr.Textbox(value="main_character", label="Primary Character") secondary_traits = gr.Textbox(value="helpful", label="Secondary Traits") blend_ratio = gr.Slider(0.1, 1.0, value=0.7, label="Primary/Secondary Ratio") - blend_output = gr.Textbox(label="Blend Protocol Prompt", interactive=False, lines=6) - blend_btn = gr.Button("๐ŸŽญ Create Blend", variant="primary") - - # Wire up all the tools - - # Original tools - wisdom_btn.click(lambda topic: creed_ai.creed_wisdom_tool(topic or "life"), inputs=[wisdom_topic], outputs=[wisdom_output]) - story_btn.click(lambda situation: creed_ai.creed_story_tool(situation or "mysterious"), inputs=[story_situation], outputs=[story_output]) - analysis_btn.click(lambda subject: creed_ai.creed_analysis_tool(subject or "business"), inputs=[analysis_subject], outputs=[analysis_output]) - conspiracy_btn.click(lambda topic: creed_ai.creed_conspiracy_tool(topic or "government"), inputs=[conspiracy_topic], outputs=[conspiracy_output]) - activate_btn.click(lambda: creed_ai.creed_mode_activate_tool(), outputs=[activate_output]) - - # Character adaptation tools - memory_btn.click(lambda facts: creed_ai.claude_persona_memory_tool("creed", facts), inputs=[memory_facts], outputs=[memory_output]) - context_btn.click(lambda summary: creed_ai.claude_persona_context_tool("creed", summary), inputs=[context_summary], outputs=[context_output]) - intensity_btn.click(lambda intensity, context: creed_ai.claude_persona_intensity_control("creed", intensity, context), inputs=[intensity_slider, intensity_context], outputs=[intensity_output]) - break_btn.click(lambda reason: creed_ai.claude_persona_break_protocol(reason), inputs=[break_reason], outputs=[break_output]) - speech_btn.click(lambda sample: creed_ai.claude_persona_speech_patterns("creed", sample), inputs=[speech_sample], outputs=[speech_output]) - knowledge_btn.click(lambda topic: creed_ai.claude_persona_knowledge_mapping("creed", topic), inputs=[knowledge_topic], outputs=[knowledge_output]) - consistency_btn.click(lambda response: creed_ai.claude_persona_consistency_check("creed", response), inputs=[consistency_response], outputs=[consistency_output]) - bridge_btn.click(lambda trait, drive: creed_ai.claude_persona_signature_bridge(trait, drive), inputs=[trait_input, drive_input], outputs=[bridge_output]) - blend_btn.click(lambda primary, secondary, ratio: creed_ai.claude_persona_blend_protocol(primary, secondary, ratio), inputs=[primary_persona, secondary_traits, blend_ratio], outputs=[blend_output]) - - # Enhanced footer - gr.HTML(""" -