Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,226 +1,117 @@
|
|
| 1 |
#!/usr/bin/env python3
|
| 2 |
"""
|
| 3 |
-
π
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
FIXED: Now provides BOTH actions and analytics in one call (peanut butter + jelly)
|
| 7 |
"""
|
| 8 |
|
| 9 |
import os
|
| 10 |
-
import gradio as gr
|
| 11 |
import torch
|
| 12 |
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 13 |
-
import time
|
| 14 |
import json
|
| 15 |
import sqlite3
|
| 16 |
import hashlib
|
| 17 |
-
from typing import List, Dict,
|
| 18 |
-
import threading
|
| 19 |
import random
|
| 20 |
-
from datetime import datetime
|
| 21 |
import logging
|
| 22 |
-
from pathlib import Path
|
| 23 |
-
|
| 24 |
-
# GPU acceleration support
|
| 25 |
-
try:
|
| 26 |
-
import spaces
|
| 27 |
-
SPACES_AVAILABLE = True
|
| 28 |
-
@spaces.GPU
|
| 29 |
-
def gpu_placeholder():
|
| 30 |
-
return "GPU acceleration available"
|
| 31 |
-
except ImportError:
|
| 32 |
-
SPACES_AVAILABLE = False
|
| 33 |
|
| 34 |
-
|
|
|
|
| 35 |
"""
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
Framework-agnostic character state management with persistence, consistency tracking,
|
| 39 |
-
and professional adaptation tools. Works with any AI system.
|
| 40 |
"""
|
| 41 |
|
| 42 |
-
def __init__(self
|
| 43 |
-
self.character_name =
|
| 44 |
-
self.model_path =
|
| 45 |
|
| 46 |
# Core AI model management
|
| 47 |
self.model = None
|
| 48 |
self.tokenizer = None
|
| 49 |
self.model_loaded = False
|
| 50 |
-
self.loading = False
|
| 51 |
self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 52 |
|
| 53 |
-
#
|
| 54 |
self.session_id = self._generate_session_id()
|
| 55 |
-
self.conversation_quality_scores = []
|
| 56 |
-
self.memory_db_path = f"{character_name}_character_memory.db"
|
| 57 |
-
|
| 58 |
-
# Cross-platform character management
|
| 59 |
-
self.character_memory = {}
|
| 60 |
-
self.persona_facts = {}
|
| 61 |
self.conversation_history = []
|
| 62 |
-
self.mcp_server=True
|
| 63 |
-
|
| 64 |
-
# Professional analytics and tracking
|
| 65 |
self.character_metrics = {
|
| 66 |
"consistency_score": 0.0,
|
| 67 |
"authenticity_score": 0.0,
|
| 68 |
"adaptation_rate": 0.0,
|
| 69 |
"memory_retention": 0.0
|
| 70 |
}
|
|
|
|
| 71 |
|
| 72 |
-
# Initialize
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
print(f"π Initializing Universal Character Manager")
|
| 76 |
-
print(f"π Character: {character_name}")
|
| 77 |
-
print(f"π§ Session ID: {self.session_id}")
|
| 78 |
print(f"π₯οΈ Device: {self.device}")
|
| 79 |
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
print(f"πΎ GPU Memory: {torch.cuda.get_device_properties(0).total_memory // 1024**3} GB")
|
| 83 |
-
|
| 84 |
-
# Load demonstration model (Creed example)
|
| 85 |
-
self.load_demonstration_model()
|
| 86 |
|
| 87 |
def _generate_session_id(self) -> str:
|
| 88 |
-
"""Generate unique session ID
|
| 89 |
timestamp = datetime.now().isoformat()
|
| 90 |
random_component = str(random.randint(1000, 9999))
|
| 91 |
return hashlib.md5(f"{timestamp}_{random_component}".encode()).hexdigest()[:12]
|
| 92 |
|
| 93 |
-
def
|
| 94 |
-
"""
|
| 95 |
try:
|
| 96 |
-
|
| 97 |
-
conn = sqlite3.connect(self.memory_db_path)
|
| 98 |
-
cursor = conn.cursor()
|
| 99 |
-
|
| 100 |
-
# Character interaction log
|
| 101 |
-
cursor.execute('''
|
| 102 |
-
CREATE TABLE IF NOT EXISTS character_interactions (
|
| 103 |
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 104 |
-
session_id TEXT,
|
| 105 |
-
user_input TEXT,
|
| 106 |
-
character_response TEXT,
|
| 107 |
-
consistency_score REAL,
|
| 108 |
-
authenticity_score REAL,
|
| 109 |
-
timestamp TEXT
|
| 110 |
-
)
|
| 111 |
-
''')
|
| 112 |
-
|
| 113 |
-
# Character state evolution
|
| 114 |
-
cursor.execute('''
|
| 115 |
-
CREATE TABLE IF NOT EXISTS character_states (
|
| 116 |
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 117 |
-
session_id TEXT,
|
| 118 |
-
character_name TEXT,
|
| 119 |
-
personality_traits TEXT,
|
| 120 |
-
memory_facts TEXT,
|
| 121 |
-
adaptation_history TEXT,
|
| 122 |
-
timestamp TEXT
|
| 123 |
-
)
|
| 124 |
-
''')
|
| 125 |
-
|
| 126 |
-
# Character performance metrics
|
| 127 |
-
cursor.execute('''
|
| 128 |
-
CREATE TABLE IF NOT EXISTS character_metrics (
|
| 129 |
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 130 |
-
session_id TEXT,
|
| 131 |
-
metric_name TEXT,
|
| 132 |
-
metric_value REAL,
|
| 133 |
-
improvement_delta REAL,
|
| 134 |
-
timestamp TEXT
|
| 135 |
-
)
|
| 136 |
-
''')
|
| 137 |
-
|
| 138 |
-
conn.commit()
|
| 139 |
-
conn.close()
|
| 140 |
-
print("β
Character persistence system initialized")
|
| 141 |
-
except Exception as e:
|
| 142 |
-
print(f"β οΈ Character persistence setup failed (non-critical): {e}")
|
| 143 |
-
|
| 144 |
-
def load_demonstration_model(self):
|
| 145 |
-
"""
|
| 146 |
-
Load demonstration model (Creed Bratton example)
|
| 147 |
-
In production: Replace with API calls to OpenAI, Anthropic, etc.
|
| 148 |
-
"""
|
| 149 |
-
if self.loading or self.model_loaded:
|
| 150 |
-
return
|
| 151 |
-
|
| 152 |
-
self.loading = True
|
| 153 |
-
|
| 154 |
-
try:
|
| 155 |
-
print(f"π§ Loading demonstration character model...")
|
| 156 |
|
| 157 |
-
print("π¦ Loading tokenizer...")
|
| 158 |
self.tokenizer = AutoTokenizer.from_pretrained(
|
| 159 |
self.model_path,
|
| 160 |
trust_remote_code=True,
|
| 161 |
padding_side="left"
|
| 162 |
)
|
| 163 |
|
| 164 |
-
# Character-specific tokens (customizable for any character)
|
| 165 |
-
character_tokens = ["<thinking>", "<memory>", "<adapt>", "<authentic>"]
|
| 166 |
-
print(f"π Adding character tokens: {character_tokens}")
|
| 167 |
-
|
| 168 |
-
num_added_tokens = self.tokenizer.add_tokens(character_tokens)
|
| 169 |
-
print(f"β
Added {num_added_tokens} character tokens")
|
| 170 |
-
|
| 171 |
if self.tokenizer.pad_token is None:
|
| 172 |
self.tokenizer.pad_token = self.tokenizer.eos_token
|
| 173 |
|
| 174 |
-
print(f"π€ Loading model...")
|
| 175 |
-
|
| 176 |
self.model = AutoModelForCausalLM.from_pretrained(
|
| 177 |
self.model_path,
|
| 178 |
torch_dtype=torch.float16,
|
| 179 |
-
device_map=
|
| 180 |
trust_remote_code=True,
|
| 181 |
low_cpu_mem_usage=True
|
| 182 |
)
|
| 183 |
|
| 184 |
-
if num_added_tokens > 0:
|
| 185 |
-
print(f"π§ Resizing model embeddings for {num_added_tokens} tokens")
|
| 186 |
-
self.model.resize_token_embeddings(len(self.tokenizer))
|
| 187 |
-
|
| 188 |
self.model.eval()
|
| 189 |
self.model_loaded = True
|
| 190 |
-
|
| 191 |
-
print(f"β
Demonstration model loaded successfully!")
|
| 192 |
|
| 193 |
except Exception as e:
|
| 194 |
-
print(f"
|
| 195 |
-
print("π‘
|
| 196 |
-
self.
|
| 197 |
|
| 198 |
-
def
|
| 199 |
-
"""
|
| 200 |
-
Generate character response using loaded model
|
| 201 |
-
In production: Replace with API calls to OpenAI, Anthropic, etc.
|
| 202 |
-
"""
|
| 203 |
|
| 204 |
if not self.model_loaded:
|
| 205 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 206 |
|
| 207 |
try:
|
| 208 |
-
#
|
| 209 |
-
current_device = next(self.model.parameters()).device
|
| 210 |
-
|
| 211 |
-
if self.device == "cuda" and current_device.type != "cuda":
|
| 212 |
-
self.model = self.model.to(self.device)
|
| 213 |
-
|
| 214 |
-
actual_device = next(self.model.parameters()).device
|
| 215 |
-
|
| 216 |
-
# Generate response
|
| 217 |
inputs = self.tokenizer.encode(conversation, return_tensors="pt")
|
| 218 |
-
|
|
|
|
| 219 |
|
| 220 |
with torch.no_grad():
|
| 221 |
outputs = self.model.generate(
|
| 222 |
inputs,
|
| 223 |
-
max_new_tokens=
|
| 224 |
do_sample=True,
|
| 225 |
temperature=temperature,
|
| 226 |
top_p=0.95,
|
|
@@ -234,401 +125,215 @@ class UniversalCharacterManager:
|
|
| 234 |
full_response = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 235 |
response = full_response[len(self.tokenizer.decode(inputs[0], skip_special_tokens=True)):].strip()
|
| 236 |
|
| 237 |
-
return self.
|
| 238 |
|
| 239 |
except Exception as e:
|
| 240 |
print(f"β Generation error: {e}")
|
| 241 |
-
return "π
|
| 242 |
-
|
| 243 |
-
def _format_character_conversation(self, message: str, history: List[List[str]]) -> str:
|
| 244 |
-
"""
|
| 245 |
-
Universal character conversation formatting
|
| 246 |
-
Easily customizable for different characters and AI systems
|
| 247 |
-
"""
|
| 248 |
-
|
| 249 |
-
# Character-specific system prompt (easily modifiable)
|
| 250 |
-
character_prompt = f"""You are {self.character_name}. Maintain character consistency.
|
| 251 |
-
Use character tokens when appropriate:
|
| 252 |
-
<thinking>for internal character thoughts</thinking>
|
| 253 |
-
<memory>for recalling past interactions</memory>
|
| 254 |
-
<adapt>for character growth moments</adapt>
|
| 255 |
-
<authentic>for core character expressions</authentic>
|
| 256 |
-
|
| 257 |
-
Character Guidelines:
|
| 258 |
-
- Stay true to established personality traits
|
| 259 |
-
- Reference past interactions naturally
|
| 260 |
-
- Show subtle character development
|
| 261 |
-
- Maintain authentic voice and mannerisms
|
| 262 |
-
"""
|
| 263 |
-
|
| 264 |
-
# Build conversation context
|
| 265 |
-
conversation = character_prompt
|
| 266 |
-
|
| 267 |
-
# Include relevant conversation history
|
| 268 |
-
for user_msg, char_msg in history[-4:]: # Configurable context window
|
| 269 |
-
conversation += f"Human: {user_msg}\n"
|
| 270 |
-
conversation += f"{self.character_name}: {char_msg}\n"
|
| 271 |
-
|
| 272 |
-
conversation += f"Human: {message}\n"
|
| 273 |
-
conversation += f"{self.character_name}:"
|
| 274 |
-
|
| 275 |
-
return conversation
|
| 276 |
|
| 277 |
-
def
|
| 278 |
-
"""
|
| 279 |
-
|
| 280 |
-
# Remove artifacts
|
| 281 |
response = response.replace("Human:", "").replace(f"{self.character_name}:", "")
|
| 282 |
-
|
| 283 |
-
# Process character tokens
|
| 284 |
-
token_formatting = {
|
| 285 |
-
"<thinking>": "\n\nπ€ **THINKING:** ",
|
| 286 |
-
"</thinking>": "\n",
|
| 287 |
-
"<memory>": "\n\nπ **REMEMBERING:** ",
|
| 288 |
-
"</memory>": "\n",
|
| 289 |
-
"<adapt>": "\n\nπ **ADAPTING:** ",
|
| 290 |
-
"</adapt>": "\n",
|
| 291 |
-
"<authentic>": "\n\n⨠**AUTHENTIC MOMENT:** ",
|
| 292 |
-
"</authentic>": "\n"
|
| 293 |
-
}
|
| 294 |
-
|
| 295 |
-
for token, replacement in token_formatting.items():
|
| 296 |
-
response = response.replace(token, replacement)
|
| 297 |
-
|
| 298 |
-
# Clean up formatting
|
| 299 |
-
response = "\n".join(line.strip() for line in response.split("\n") if line.strip())
|
| 300 |
|
| 301 |
if response and not response.endswith(('.', '!', '?', '...', '*')):
|
| 302 |
response += "."
|
| 303 |
|
| 304 |
return response
|
| 305 |
|
| 306 |
-
def
|
| 307 |
-
"""
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
for artifact in artifacts:
|
| 316 |
-
if artifact in response:
|
| 317 |
-
score -= 0.3
|
| 318 |
-
|
| 319 |
-
# Analyze response length appropriateness
|
| 320 |
-
words = response.split()
|
| 321 |
-
if len(words) > 100: # Too verbose
|
| 322 |
-
score -= 0.1
|
| 323 |
-
elif len(words) < 5: # Too brief
|
| 324 |
-
score -= 0.2
|
| 325 |
-
|
| 326 |
-
# Check for repetition
|
| 327 |
-
if len(words) > 5:
|
| 328 |
-
unique_ratio = len(set(words)) / len(words)
|
| 329 |
-
if unique_ratio < 0.7:
|
| 330 |
-
score -= 0.2
|
| 331 |
-
|
| 332 |
-
return max(0.0, min(1.0, score))
|
| 333 |
-
|
| 334 |
-
def _analyze_response_authenticity(self, response: str) -> float:
|
| 335 |
-
"""Analyze how authentic the response feels for the character"""
|
| 336 |
-
# This would be customized based on the specific character
|
| 337 |
-
# For demonstration purposes, using Creed-specific authenticity markers
|
| 338 |
-
|
| 339 |
-
authenticity_markers = {
|
| 340 |
-
"positive": ["quarry", "mung", "sheriff", "fake", "mysterious", "business"],
|
| 341 |
-
"neutral": ["office", "work", "people", "time", "know"],
|
| 342 |
-
"negative": ["modern", "technology", "app", "social media", "smartphone"]
|
| 343 |
}
|
| 344 |
|
| 345 |
-
|
| 346 |
|
| 347 |
-
|
|
|
|
| 348 |
|
| 349 |
-
#
|
| 350 |
-
for
|
| 351 |
-
|
| 352 |
-
|
| 353 |
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
if marker in response_lower:
|
| 357 |
-
score -= 0.15
|
| 358 |
|
| 359 |
-
return
|
| 360 |
|
| 361 |
-
def
|
| 362 |
-
"""
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 370 |
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
self.character_metrics["adaptation_rate"] = recent_avg - older_avg
|
| 376 |
-
|
| 377 |
-
def _store_character_interaction(self, user_input: str, response: str, consistency: float, authenticity: float):
|
| 378 |
-
"""Store interaction in character persistence system"""
|
| 379 |
-
try:
|
| 380 |
-
conn = sqlite3.connect(self.memory_db_path)
|
| 381 |
-
cursor = conn.cursor()
|
| 382 |
-
|
| 383 |
-
cursor.execute('''
|
| 384 |
-
INSERT INTO character_interactions
|
| 385 |
-
(session_id, user_input, character_response, consistency_score, authenticity_score, timestamp)
|
| 386 |
-
VALUES (?, ?, ?, ?, ?, ?)
|
| 387 |
-
''', (
|
| 388 |
-
self.session_id,
|
| 389 |
-
user_input,
|
| 390 |
-
response,
|
| 391 |
-
consistency,
|
| 392 |
-
authenticity,
|
| 393 |
-
datetime.now().isoformat()
|
| 394 |
-
))
|
| 395 |
-
|
| 396 |
-
conn.commit()
|
| 397 |
-
conn.close()
|
| 398 |
-
except Exception as e:
|
| 399 |
-
print(f"β οΈ Character persistence failed (non-critical): {e}")
|
| 400 |
-
|
| 401 |
-
def get_character_analytics(self) -> Dict[str, Any]:
|
| 402 |
-
"""Get comprehensive character performance analytics"""
|
| 403 |
-
try:
|
| 404 |
-
conn = sqlite3.connect(self.memory_db_path)
|
| 405 |
-
cursor = conn.cursor()
|
| 406 |
-
|
| 407 |
-
# Session statistics
|
| 408 |
-
cursor.execute('''
|
| 409 |
-
SELECT
|
| 410 |
-
AVG(consistency_score),
|
| 411 |
-
AVG(authenticity_score),
|
| 412 |
-
COUNT(*),
|
| 413 |
-
MAX(timestamp)
|
| 414 |
-
FROM character_interactions
|
| 415 |
-
WHERE session_id = ?
|
| 416 |
-
''', (self.session_id,))
|
| 417 |
-
|
| 418 |
-
result = cursor.fetchone()
|
| 419 |
-
avg_consistency = result[0] if result[0] else 0.0
|
| 420 |
-
avg_authenticity = result[1] if result[1] else 0.0
|
| 421 |
-
interaction_count = result[2]
|
| 422 |
-
last_interaction = result[3]
|
| 423 |
-
|
| 424 |
-
# Recent performance trend
|
| 425 |
-
cursor.execute('''
|
| 426 |
-
SELECT consistency_score, authenticity_score
|
| 427 |
-
FROM character_interactions
|
| 428 |
-
WHERE session_id = ?
|
| 429 |
-
ORDER BY timestamp DESC LIMIT 10
|
| 430 |
-
''', (self.session_id,))
|
| 431 |
-
|
| 432 |
-
recent_scores = cursor.fetchall()
|
| 433 |
-
|
| 434 |
-
conn.close()
|
| 435 |
-
|
| 436 |
-
return {
|
| 437 |
-
"session_id": self.session_id,
|
| 438 |
-
"character_name": self.character_name,
|
| 439 |
-
"total_interactions": interaction_count,
|
| 440 |
-
"avg_consistency": round(avg_consistency, 3),
|
| 441 |
-
"avg_authenticity": round(avg_authenticity, 3),
|
| 442 |
-
"last_interaction": last_interaction,
|
| 443 |
-
"recent_performance": recent_scores,
|
| 444 |
-
"current_metrics": self.character_metrics,
|
| 445 |
-
"improvement_trend": "improving" if self.character_metrics["adaptation_rate"] > 0 else "stable"
|
| 446 |
-
}
|
| 447 |
-
|
| 448 |
-
except Exception as e:
|
| 449 |
-
return {"error": str(e)}
|
| 450 |
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
def creed_interact_with_analytics(
|
| 455 |
-
self,
|
| 456 |
-
message: str,
|
| 457 |
-
context: str = "office",
|
| 458 |
-
temperature: float = 0.9
|
| 459 |
-
) -> Dict[str, Any]:
|
| 460 |
-
"""
|
| 461 |
-
THE FIXED INTERFACE: Peanut Butter (Actions) + Jelly (Analytics)
|
| 462 |
-
|
| 463 |
-
Args:
|
| 464 |
-
message: What you want to say to Creed
|
| 465 |
-
context: Conversation setting (office, mysterious, business, etc.)
|
| 466 |
-
temperature: Response randomness (0.1 = focused, 0.9 = chaotic Creed)
|
| 467 |
-
|
| 468 |
-
Returns:
|
| 469 |
-
Complete response with actions AND analytics
|
| 470 |
-
"""
|
| 471 |
-
|
| 472 |
-
if not self.model_loaded:
|
| 473 |
-
return {
|
| 474 |
-
"creed_response": "π Character system loading or not available. In production, this would call your AI API.",
|
| 475 |
-
"success": False,
|
| 476 |
-
"error": "Model not loaded",
|
| 477 |
-
"session_analytics": self.get_character_analytics()
|
| 478 |
-
}
|
| 479 |
-
|
| 480 |
-
try:
|
| 481 |
-
# THE ACTION PART (Peanut Butter) - Actually DO something
|
| 482 |
-
conversation = self._format_character_conversation(message, self.conversation_history)
|
| 483 |
-
|
| 484 |
-
# Add context-specific character adjustments
|
| 485 |
-
if context == "mysterious":
|
| 486 |
-
conversation += "\n[Creed feels particularly mysterious and cryptic today]"
|
| 487 |
-
elif context == "business":
|
| 488 |
-
conversation += "\n[Creed is in 'business mode' - still Creed, but focused]"
|
| 489 |
-
elif context == "paranoid":
|
| 490 |
-
conversation += "\n[Creed suspects someone might be listening]"
|
| 491 |
-
|
| 492 |
-
# Generate the actual response
|
| 493 |
-
response = self.generate_character_response(conversation, temperature)
|
| 494 |
-
|
| 495 |
-
# Analyze response quality
|
| 496 |
-
consistency_score = self._analyze_response_consistency(response)
|
| 497 |
-
authenticity_score = self._analyze_response_authenticity(response)
|
| 498 |
-
|
| 499 |
-
# Update character metrics
|
| 500 |
-
self._update_character_metrics(consistency_score, authenticity_score)
|
| 501 |
-
|
| 502 |
-
# Store interaction for persistence
|
| 503 |
-
self._store_character_interaction(message, response, consistency_score, authenticity_score)
|
| 504 |
-
|
| 505 |
-
# Update conversation history
|
| 506 |
-
self.conversation_history.append([message, response])
|
| 507 |
-
if len(self.conversation_history) > 10: # Keep last 10 exchanges
|
| 508 |
-
self.conversation_history = self.conversation_history[-10:]
|
| 509 |
-
|
| 510 |
-
# THE ANALYTICS PART (Jelly) - Measure what happened
|
| 511 |
-
analytics = self.get_character_analytics()
|
| 512 |
-
|
| 513 |
-
# THE BEAUTIFUL SANDWICH - Return both action and analytics
|
| 514 |
-
return {
|
| 515 |
-
"creed_response": response,
|
| 516 |
-
"success": True,
|
| 517 |
-
"interaction_metrics": {
|
| 518 |
-
"consistency_score": round(consistency_score, 3),
|
| 519 |
-
"authenticity_score": round(authenticity_score, 3),
|
| 520 |
-
"response_length": len(response.split()),
|
| 521 |
-
"context_used": context,
|
| 522 |
-
"temperature_used": temperature
|
| 523 |
-
},
|
| 524 |
-
"session_analytics": analytics,
|
| 525 |
-
"character_insights": self._generate_character_insights(response, consistency_score, authenticity_score),
|
| 526 |
-
"conversation_history_length": len(self.conversation_history)
|
| 527 |
-
}
|
| 528 |
-
|
| 529 |
-
except Exception as e:
|
| 530 |
-
return {
|
| 531 |
-
"creed_response": f"π Character processing encountered an issue: {str(e)}",
|
| 532 |
-
"success": False,
|
| 533 |
-
"error": str(e),
|
| 534 |
-
"session_analytics": self.get_character_analytics()
|
| 535 |
-
}
|
| 536 |
-
|
| 537 |
-
def _generate_character_insights(self, response: str, consistency: float, authenticity: float) -> str:
|
| 538 |
-
"""Generate insights about the character's current state"""
|
| 539 |
-
|
| 540 |
-
insights = []
|
| 541 |
-
|
| 542 |
-
if consistency > 0.8:
|
| 543 |
-
insights.append("π― High consistency - Creed is staying true to character")
|
| 544 |
-
elif consistency < 0.5:
|
| 545 |
-
insights.append("β οΈ Low consistency - Character may be drifting")
|
| 546 |
-
|
| 547 |
-
if authenticity > 0.7:
|
| 548 |
-
insights.append("β¨ High authenticity - Peak Creed behavior detected")
|
| 549 |
-
elif authenticity < 0.4:
|
| 550 |
-
insights.append("π Low authenticity - Response feels generic")
|
| 551 |
-
|
| 552 |
-
if "mysterious" in response.lower() or "secret" in response.lower():
|
| 553 |
-
insights.append("π΅οΈ Mystery mode activated - Creed is being extra cryptic")
|
| 554 |
-
|
| 555 |
-
if len(response.split()) > 50:
|
| 556 |
-
insights.append("π Verbose mode - Creed is feeling chatty")
|
| 557 |
-
elif len(response.split()) < 15:
|
| 558 |
-
insights.append("π€ Concise mode - Creed is being unusually brief")
|
| 559 |
-
|
| 560 |
-
return " | ".join(insights) if insights else "π Standard Creed operating parameters"
|
| 561 |
|
| 562 |
-
# =================== MCP TOOL
|
| 563 |
-
#
|
| 564 |
|
| 565 |
-
def
|
| 566 |
-
message: str
|
| 567 |
-
context: str = "office",
|
| 568 |
temperature: float = 0.9
|
| 569 |
) -> dict:
|
| 570 |
"""
|
| 571 |
-
|
| 572 |
-
|
| 573 |
-
The Perfect Sandwich: Actions + Analytics in one call
|
| 574 |
-
No more status-only responses!
|
| 575 |
|
| 576 |
Args:
|
| 577 |
message: What to say to Creed
|
| 578 |
context: office, mysterious, business, paranoid
|
| 579 |
-
temperature: 0.1
|
| 580 |
|
| 581 |
Returns:
|
| 582 |
-
Complete interaction with response and
|
| 583 |
"""
|
| 584 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 585 |
try:
|
| 586 |
-
#
|
| 587 |
-
|
| 588 |
|
| 589 |
-
|
| 590 |
-
|
| 591 |
-
|
| 592 |
-
|
| 593 |
-
|
| 594 |
-
"usage_example": "Call with message='Hey Creed, what are you working on?'",
|
| 595 |
-
"available_contexts": ["office", "mysterious", "business", "paranoid"],
|
| 596 |
-
"session_analytics": analytics,
|
| 597 |
-
"ready_for_interaction": True
|
| 598 |
-
}
|
| 599 |
|
| 600 |
-
#
|
| 601 |
-
|
|
|
|
|
|
|
| 602 |
|
| 603 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 604 |
|
| 605 |
except Exception as e:
|
| 606 |
return {
|
| 607 |
-
"error": f"
|
| 608 |
-
"
|
| 609 |
-
"
|
| 610 |
}
|
| 611 |
|
| 612 |
-
|
| 613 |
-
|
| 614 |
-
|
| 615 |
-
|
| 616 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 617 |
|
| 618 |
if __name__ == "__main__":
|
| 619 |
-
|
| 620 |
-
print("
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 621 |
|
| 622 |
-
# Test
|
| 623 |
-
|
| 624 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 625 |
|
| 626 |
-
|
| 627 |
-
result2 = creed_thoughts_fixed_interface(
|
| 628 |
-
message="Hey Creed, what's your take on office productivity?",
|
| 629 |
-
context="business",
|
| 630 |
-
temperature=0.8
|
| 631 |
-
)
|
| 632 |
-
print("\nActual Interaction:", result2["creed_response"])
|
| 633 |
-
print("Metrics:", result2["interaction_metrics"])
|
| 634 |
-
print("Insights:", result2["character_insights"])
|
|
|
|
| 1 |
#!/usr/bin/env python3
|
| 2 |
"""
|
| 3 |
+
π Creed Character MCP Server - PURE MCP MODE
|
| 4 |
+
No web UI confusion - just clean MCP tool endpoints
|
|
|
|
|
|
|
| 5 |
"""
|
| 6 |
|
| 7 |
import os
|
|
|
|
| 8 |
import torch
|
| 9 |
from transformers import AutoTokenizer, AutoModelForCausalLM
|
|
|
|
| 10 |
import json
|
| 11 |
import sqlite3
|
| 12 |
import hashlib
|
| 13 |
+
from typing import List, Dict, Optional, Any
|
|
|
|
| 14 |
import random
|
| 15 |
+
from datetime import datetime
|
| 16 |
import logging
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
+
# Simplified character manager for MCP-only operation
|
| 19 |
+
class CreedCharacterManager:
|
| 20 |
"""
|
| 21 |
+
Simplified Creed Character Manager - MCP Server Mode Only
|
| 22 |
+
No Gradio, no web UI, just pure character interaction functionality
|
|
|
|
|
|
|
| 23 |
"""
|
| 24 |
|
| 25 |
+
def __init__(self):
|
| 26 |
+
self.character_name = "creed"
|
| 27 |
+
self.model_path = "phxdev/creed-qwen-0.5b-lora"
|
| 28 |
|
| 29 |
# Core AI model management
|
| 30 |
self.model = None
|
| 31 |
self.tokenizer = None
|
| 32 |
self.model_loaded = False
|
|
|
|
| 33 |
self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 34 |
|
| 35 |
+
# Session management
|
| 36 |
self.session_id = self._generate_session_id()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
self.conversation_history = []
|
|
|
|
|
|
|
|
|
|
| 38 |
self.character_metrics = {
|
| 39 |
"consistency_score": 0.0,
|
| 40 |
"authenticity_score": 0.0,
|
| 41 |
"adaptation_rate": 0.0,
|
| 42 |
"memory_retention": 0.0
|
| 43 |
}
|
| 44 |
+
self.mcp_server = True
|
| 45 |
|
| 46 |
+
# Initialize system
|
| 47 |
+
print(f"π Initializing Creed Character MCP Server")
|
| 48 |
+
print(f"π Session ID: {self.session_id}")
|
|
|
|
|
|
|
|
|
|
| 49 |
print(f"π₯οΈ Device: {self.device}")
|
| 50 |
|
| 51 |
+
# Load model asynchronously to avoid blocking MCP startup
|
| 52 |
+
self._attempt_model_load()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
|
| 54 |
def _generate_session_id(self) -> str:
|
| 55 |
+
"""Generate unique session ID"""
|
| 56 |
timestamp = datetime.now().isoformat()
|
| 57 |
random_component = str(random.randint(1000, 9999))
|
| 58 |
return hashlib.md5(f"{timestamp}_{random_component}".encode()).hexdigest()[:12]
|
| 59 |
|
| 60 |
+
def _attempt_model_load(self):
|
| 61 |
+
"""Attempt to load model without blocking initialization"""
|
| 62 |
try:
|
| 63 |
+
print("π§ Loading Creed character model...")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
|
|
|
|
| 65 |
self.tokenizer = AutoTokenizer.from_pretrained(
|
| 66 |
self.model_path,
|
| 67 |
trust_remote_code=True,
|
| 68 |
padding_side="left"
|
| 69 |
)
|
| 70 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
if self.tokenizer.pad_token is None:
|
| 72 |
self.tokenizer.pad_token = self.tokenizer.eos_token
|
| 73 |
|
|
|
|
|
|
|
| 74 |
self.model = AutoModelForCausalLM.from_pretrained(
|
| 75 |
self.model_path,
|
| 76 |
torch_dtype=torch.float16,
|
| 77 |
+
device_map="auto" if torch.cuda.is_available() else None,
|
| 78 |
trust_remote_code=True,
|
| 79 |
low_cpu_mem_usage=True
|
| 80 |
)
|
| 81 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
self.model.eval()
|
| 83 |
self.model_loaded = True
|
| 84 |
+
print("β
Creed character model loaded successfully!")
|
|
|
|
| 85 |
|
| 86 |
except Exception as e:
|
| 87 |
+
print(f"β οΈ Model loading failed: {e}")
|
| 88 |
+
print("π‘ Running in simulation mode - responses will be simulated")
|
| 89 |
+
self.model_loaded = False
|
| 90 |
|
| 91 |
+
def generate_creed_response(self, conversation: str, temperature: float = 0.9) -> str:
|
| 92 |
+
"""Generate character response"""
|
|
|
|
|
|
|
|
|
|
| 93 |
|
| 94 |
if not self.model_loaded:
|
| 95 |
+
# Fallback simulated responses for testing
|
| 96 |
+
simulated_responses = [
|
| 97 |
+
"Well well well. I've been expecting this question. Or have I?",
|
| 98 |
+
"You know, I was just thinking about that exact thing. Or was I thinking about mung beans? Hard to tell sometimes.",
|
| 99 |
+
"Interesting question. Reminds me of the time I solved a murder that may or may not have happened.",
|
| 100 |
+
"That's classified information. But between you and me... *whispers mysteriously* ...I don't actually know either.",
|
| 101 |
+
"I've got three theories about this, but I can only tell you two of them. The third one involves the vending machine on the second floor."
|
| 102 |
+
]
|
| 103 |
+
return random.choice(simulated_responses)
|
| 104 |
|
| 105 |
try:
|
| 106 |
+
# Generate actual response using model
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
inputs = self.tokenizer.encode(conversation, return_tensors="pt")
|
| 108 |
+
if torch.cuda.is_available():
|
| 109 |
+
inputs = inputs.to(self.device)
|
| 110 |
|
| 111 |
with torch.no_grad():
|
| 112 |
outputs = self.model.generate(
|
| 113 |
inputs,
|
| 114 |
+
max_new_tokens=150,
|
| 115 |
do_sample=True,
|
| 116 |
temperature=temperature,
|
| 117 |
top_p=0.95,
|
|
|
|
| 125 |
full_response = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 126 |
response = full_response[len(self.tokenizer.decode(inputs[0], skip_special_tokens=True)):].strip()
|
| 127 |
|
| 128 |
+
return self._process_response(response)
|
| 129 |
|
| 130 |
except Exception as e:
|
| 131 |
print(f"β Generation error: {e}")
|
| 132 |
+
return "π My digital consciousness is experiencing technical difficulties. Please try again."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
|
| 134 |
+
def _process_response(self, response: str) -> str:
|
| 135 |
+
"""Clean up response"""
|
|
|
|
|
|
|
| 136 |
response = response.replace("Human:", "").replace(f"{self.character_name}:", "")
|
| 137 |
+
response = response.strip()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 138 |
|
| 139 |
if response and not response.endswith(('.', '!', '?', '...', '*')):
|
| 140 |
response += "."
|
| 141 |
|
| 142 |
return response
|
| 143 |
|
| 144 |
+
def _format_conversation(self, message: str, context: str = "office") -> str:
|
| 145 |
+
"""Format conversation for character"""
|
| 146 |
+
|
| 147 |
+
# Context-specific prompts
|
| 148 |
+
context_prompts = {
|
| 149 |
+
"office": "You are Creed Bratton from The Office. Respond in character with your unique mysterious and unpredictable personality.",
|
| 150 |
+
"mysterious": "You are Creed Bratton feeling particularly mysterious and cryptic today. Be extra enigmatic.",
|
| 151 |
+
"business": "You are Creed Bratton in business mode - still weird, but focused on work-related topics.",
|
| 152 |
+
"paranoid": "You are Creed Bratton feeling paranoid. Someone might be listening."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
}
|
| 154 |
|
| 155 |
+
prompt = context_prompts.get(context, context_prompts["office"])
|
| 156 |
|
| 157 |
+
# Build conversation
|
| 158 |
+
conversation = f"{prompt}\n"
|
| 159 |
|
| 160 |
+
# Add recent history
|
| 161 |
+
for user_msg, creed_msg in self.conversation_history[-3:]:
|
| 162 |
+
conversation += f"Human: {user_msg}\n"
|
| 163 |
+
conversation += f"Creed: {creed_msg}\n"
|
| 164 |
|
| 165 |
+
conversation += f"Human: {message}\n"
|
| 166 |
+
conversation += "Creed:"
|
|
|
|
|
|
|
| 167 |
|
| 168 |
+
return conversation
|
| 169 |
|
| 170 |
+
def _calculate_metrics(self, response: str) -> Dict[str, float]:
|
| 171 |
+
"""Calculate response metrics"""
|
| 172 |
+
|
| 173 |
+
# Simple consistency check
|
| 174 |
+
consistency = 1.0
|
| 175 |
+
if len(response.split()) < 5:
|
| 176 |
+
consistency -= 0.3
|
| 177 |
+
if any(word in response.lower() for word in ["ai", "assistant", "model"]):
|
| 178 |
+
consistency -= 0.4
|
| 179 |
+
consistency = max(0.0, min(1.0, consistency))
|
| 180 |
+
|
| 181 |
+
# Simple authenticity check
|
| 182 |
+
authenticity = 0.5
|
| 183 |
+
creed_markers = ["mysterious", "business", "quarry", "mung", "fake", "sheriff"]
|
| 184 |
+
for marker in creed_markers:
|
| 185 |
+
if marker in response.lower():
|
| 186 |
+
authenticity += 0.1
|
| 187 |
+
authenticity = max(0.0, min(1.0, authenticity))
|
| 188 |
|
| 189 |
+
return {
|
| 190 |
+
"consistency_score": round(consistency, 3),
|
| 191 |
+
"authenticity_score": round(authenticity, 3)
|
| 192 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 193 |
|
| 194 |
+
# Global manager instance
|
| 195 |
+
creed_manager = CreedCharacterManager()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 196 |
|
| 197 |
+
# =================== MCP TOOL FUNCTIONS ===================
|
| 198 |
+
# These are the actual functions exposed to the MCP system
|
| 199 |
|
| 200 |
+
def creed_interact(
|
| 201 |
+
message: str,
|
| 202 |
+
context: str = "office",
|
| 203 |
temperature: float = 0.9
|
| 204 |
) -> dict:
|
| 205 |
"""
|
| 206 |
+
PRIMARY MCP TOOL: Interact with Creed Bratton character
|
|
|
|
|
|
|
|
|
|
| 207 |
|
| 208 |
Args:
|
| 209 |
message: What to say to Creed
|
| 210 |
context: office, mysterious, business, paranoid
|
| 211 |
+
temperature: Response randomness (0.1-0.9)
|
| 212 |
|
| 213 |
Returns:
|
| 214 |
+
Complete interaction with response and metrics
|
| 215 |
"""
|
| 216 |
|
| 217 |
+
if not message or not message.strip():
|
| 218 |
+
return {
|
| 219 |
+
"error": "No message provided",
|
| 220 |
+
"usage": "Provide a message to interact with Creed",
|
| 221 |
+
"example": "creed_interact('Hey Creed, what are you working on?')",
|
| 222 |
+
"available_contexts": ["office", "mysterious", "business", "paranoid"]
|
| 223 |
+
}
|
| 224 |
+
|
| 225 |
try:
|
| 226 |
+
# Format conversation
|
| 227 |
+
conversation = creed_manager._format_conversation(message, context)
|
| 228 |
|
| 229 |
+
# Generate response
|
| 230 |
+
response = creed_manager.generate_creed_response(conversation, temperature)
|
| 231 |
+
|
| 232 |
+
# Calculate metrics
|
| 233 |
+
metrics = creed_manager._calculate_metrics(response)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 234 |
|
| 235 |
+
# Update conversation history
|
| 236 |
+
creed_manager.conversation_history.append([message, response])
|
| 237 |
+
if len(creed_manager.conversation_history) > 10:
|
| 238 |
+
creed_manager.conversation_history = creed_manager.conversation_history[-10:]
|
| 239 |
|
| 240 |
+
# Update character metrics
|
| 241 |
+
creed_manager.character_metrics.update(metrics)
|
| 242 |
+
|
| 243 |
+
return {
|
| 244 |
+
"creed_response": response,
|
| 245 |
+
"success": True,
|
| 246 |
+
"metrics": metrics,
|
| 247 |
+
"context_used": context,
|
| 248 |
+
"temperature_used": temperature,
|
| 249 |
+
"conversation_length": len(creed_manager.conversation_history),
|
| 250 |
+
"session_id": creed_manager.session_id
|
| 251 |
+
}
|
| 252 |
|
| 253 |
except Exception as e:
|
| 254 |
return {
|
| 255 |
+
"error": f"Creed interaction failed: {str(e)}",
|
| 256 |
+
"success": False,
|
| 257 |
+
"creed_response": "π My digital consciousness encountered an error. Very mysterious."
|
| 258 |
}
|
| 259 |
|
| 260 |
+
def creed_status() -> dict:
|
| 261 |
+
"""
|
| 262 |
+
SECONDARY MCP TOOL: Get Creed character system status
|
| 263 |
+
|
| 264 |
+
Returns:
|
| 265 |
+
Current system status and analytics
|
| 266 |
+
"""
|
| 267 |
+
|
| 268 |
+
return {
|
| 269 |
+
"status": "active",
|
| 270 |
+
"character_name": "creed",
|
| 271 |
+
"session_id": creed_manager.session_id,
|
| 272 |
+
"model_loaded": creed_manager.model_loaded,
|
| 273 |
+
"device": creed_manager.device,
|
| 274 |
+
"conversation_history_length": len(creed_manager.conversation_history),
|
| 275 |
+
"current_metrics": creed_manager.character_metrics,
|
| 276 |
+
"available_functions": ["creed_interact", "creed_status", "creed_context_options"],
|
| 277 |
+
"system_ready": True
|
| 278 |
+
}
|
| 279 |
+
|
| 280 |
+
def creed_context_options() -> dict:
|
| 281 |
+
"""
|
| 282 |
+
UTILITY MCP TOOL: Get available context options for Creed interactions
|
| 283 |
+
|
| 284 |
+
Returns:
|
| 285 |
+
Available context modes and descriptions
|
| 286 |
+
"""
|
| 287 |
+
|
| 288 |
+
return {
|
| 289 |
+
"available_contexts": {
|
| 290 |
+
"office": "Standard Creed - mysterious office personality",
|
| 291 |
+
"mysterious": "Extra cryptic and enigmatic Creed",
|
| 292 |
+
"business": "Creed in work mode - still weird but focused",
|
| 293 |
+
"paranoid": "Creed feeling suspicious and paranoid"
|
| 294 |
+
},
|
| 295 |
+
"temperature_range": {
|
| 296 |
+
"min": 0.1,
|
| 297 |
+
"max": 0.9,
|
| 298 |
+
"recommended": 0.8,
|
| 299 |
+
"description": "Higher = more chaotic, Lower = more focused"
|
| 300 |
+
},
|
| 301 |
+
"usage_example": {
|
| 302 |
+
"function": "creed_interact",
|
| 303 |
+
"parameters": {
|
| 304 |
+
"message": "Hey Creed, what's the strangest thing in the office today?",
|
| 305 |
+
"context": "mysterious",
|
| 306 |
+
"temperature": 0.8
|
| 307 |
+
}
|
| 308 |
+
}
|
| 309 |
+
}
|
| 310 |
+
|
| 311 |
+
# Initialize logging
|
| 312 |
+
logging.basicConfig(level=logging.INFO)
|
| 313 |
+
logger = logging.getLogger(__name__)
|
| 314 |
|
| 315 |
if __name__ == "__main__":
|
| 316 |
+
print("π Creed Character MCP Server Starting...")
|
| 317 |
+
print("π Available MCP Tools:")
|
| 318 |
+
print(" β’ creed_interact(message, context, temperature)")
|
| 319 |
+
print(" β’ creed_status()")
|
| 320 |
+
print(" β’ creed_context_options()")
|
| 321 |
+
print(f"π Session ID: {creed_manager.session_id}")
|
| 322 |
+
print("β
MCP Server Ready")
|
| 323 |
+
|
| 324 |
+
# Test the functions
|
| 325 |
+
print("\nπ§ͺ Testing MCP Tools...")
|
| 326 |
+
|
| 327 |
+
# Test status
|
| 328 |
+
status = creed_status()
|
| 329 |
+
print(f"Status: {status['status']} | Model Loaded: {status['model_loaded']}")
|
| 330 |
|
| 331 |
+
# Test interaction
|
| 332 |
+
test_result = creed_interact("Hey Creed, test message", "office", 0.8)
|
| 333 |
+
if test_result.get("success"):
|
| 334 |
+
print(f"Test Response: {test_result['creed_response']}")
|
| 335 |
+
print(f"Metrics: {test_result['metrics']}")
|
| 336 |
+
else:
|
| 337 |
+
print(f"Test Error: {test_result.get('error')}")
|
| 338 |
|
| 339 |
+
print("\nπ MCP Server initialization complete!")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|