Spaces:
Running
Running
Upload 4 files
Browse files- services/chat_service.py +41 -0
- services/memory_service.py +44 -0
- services/model_service.py +52 -0
- services/persona_service.py +32 -0
services/chat_service.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Chat Service - Handles all chat logic
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from typing import Dict
|
| 6 |
+
import models.registry as model_registry
|
| 7 |
+
from services.memory_service import MemoryService
|
| 8 |
+
from services.persona_service import PersonaService
|
| 9 |
+
from services.model_service import ModelService
|
| 10 |
+
|
| 11 |
+
class ChatService:
|
| 12 |
+
@staticmethod
|
| 13 |
+
async def process_message(user_id: str, message: str, model_id: str, **kwargs) -> Dict:
|
| 14 |
+
try:
|
| 15 |
+
model_cfg = model_registry.get(model_id)
|
| 16 |
+
|
| 17 |
+
# Get persona
|
| 18 |
+
persona = kwargs.get("persona", "default")
|
| 19 |
+
persona_data = PersonaService.get_persona(persona)
|
| 20 |
+
|
| 21 |
+
# Load memory
|
| 22 |
+
memory = MemoryService.load_recent_memory(user_id, 8)
|
| 23 |
+
|
| 24 |
+
# Call model-specific logic
|
| 25 |
+
result = await ModelService.get_model_response(
|
| 26 |
+
user_id=user_id,
|
| 27 |
+
message=message,
|
| 28 |
+
model_id=model_id,
|
| 29 |
+
persona=persona_data,
|
| 30 |
+
memory=memory,
|
| 31 |
+
**kwargs
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
return result
|
| 35 |
+
|
| 36 |
+
except Exception as e:
|
| 37 |
+
logging.error(f"[ChatService] Error: {e}")
|
| 38 |
+
return {
|
| 39 |
+
"response": "π Something went wrong. Please try again.",
|
| 40 |
+
"error": True
|
| 41 |
+
}
|
services/memory_service.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Memory Service - Robust memory management
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from datetime import datetime, timezone
|
| 6 |
+
from typing import Dict, List
|
| 7 |
+
from database import long_term_memory_col, chat_history_col
|
| 8 |
+
|
| 9 |
+
class MemoryService:
|
| 10 |
+
@staticmethod
|
| 11 |
+
def load_long_memory(user_id: str) -> Dict:
|
| 12 |
+
try:
|
| 13 |
+
return long_term_memory_col.find_one({"user_id": user_id}) or {}
|
| 14 |
+
except Exception as e:
|
| 15 |
+
logging.error(f"[Memory] Load failed: {e}")
|
| 16 |
+
return {}
|
| 17 |
+
|
| 18 |
+
@staticmethod
|
| 19 |
+
def save_fact(user_id: str, key: str, value: str):
|
| 20 |
+
try:
|
| 21 |
+
long_term_memory_col.update_one(
|
| 22 |
+
{"user_id": user_id},
|
| 23 |
+
{"$set": {key: value, "last_updated": datetime.now(timezone.utc)}},
|
| 24 |
+
upsert=True
|
| 25 |
+
)
|
| 26 |
+
except Exception as e:
|
| 27 |
+
logging.error(f"[Memory] Save failed: {e}")
|
| 28 |
+
|
| 29 |
+
@staticmethod
|
| 30 |
+
def load_recent_memory(user_id: str, limit: int = 8) -> List[Dict]:
|
| 31 |
+
try:
|
| 32 |
+
cursor = chat_history_col.find({"user_id": user_id}).sort("timestamp", -1).limit(limit * 2)
|
| 33 |
+
msgs = list(cursor)
|
| 34 |
+
msgs.reverse()
|
| 35 |
+
pairs = []
|
| 36 |
+
for msg in msgs:
|
| 37 |
+
if msg["role"] == "user":
|
| 38 |
+
pairs.append({"user": msg["content"], "ai": ""})
|
| 39 |
+
elif msg["role"] == "assistant" and pairs:
|
| 40 |
+
pairs[-1]["ai"] = msg["content"]
|
| 41 |
+
return [p for p in pairs if p["ai"]]
|
| 42 |
+
except Exception as e:
|
| 43 |
+
logging.error(f"[Memory] Load recent failed: {e}")
|
| 44 |
+
return []
|
services/model_service.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Model Service - Each model handles its own logic
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import models.registry as model_registry
|
| 6 |
+
|
| 7 |
+
class ModelService:
|
| 8 |
+
@staticmethod
|
| 9 |
+
async def get_model_response(user_id: str, message: str, model_id: str, **kwargs) -> dict:
|
| 10 |
+
try:
|
| 11 |
+
model_cfg = model_registry.get(model_id)
|
| 12 |
+
|
| 13 |
+
if "r1" in model_id.lower():
|
| 14 |
+
return await ModelService._handle_r1(user_id, message, model_cfg, **kwargs)
|
| 15 |
+
elif "vision" in model_id.lower():
|
| 16 |
+
return await ModelService._handle_vision(user_id, message, model_cfg, **kwargs)
|
| 17 |
+
else:
|
| 18 |
+
return await ModelService._handle_default(user_id, message, model_cfg, **kwargs)
|
| 19 |
+
|
| 20 |
+
except Exception as e:
|
| 21 |
+
logging.error(f"[ModelService] Error for {model_id}: {e}")
|
| 22 |
+
return {
|
| 23 |
+
"response": "Model temporarily unavailable. Please try again.",
|
| 24 |
+
"error": True,
|
| 25 |
+
"model": model_id
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
@staticmethod
|
| 29 |
+
async def _handle_r1(user_id, message, model_cfg, **kwargs):
|
| 30 |
+
# R1 specific: Deep thinking + dataset examples
|
| 31 |
+
return {
|
| 32 |
+
"response": f"[R1 Deep Think] {message[:120]}...",
|
| 33 |
+
"model": model_cfg["display_name"],
|
| 34 |
+
"mode": "deep_think"
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
@staticmethod
|
| 38 |
+
async def _handle_vision(user_id, message, model_cfg, **kwargs):
|
| 39 |
+
# Vision specific logic
|
| 40 |
+
return {
|
| 41 |
+
"response": f"[Vision Analysis] {message[:100]}...",
|
| 42 |
+
"model": model_cfg["display_name"],
|
| 43 |
+
"mode": "vision"
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
@staticmethod
|
| 47 |
+
async def _handle_default(user_id, message, model_cfg, **kwargs):
|
| 48 |
+
return {
|
| 49 |
+
"response": f"[Default] {message[:100]}...",
|
| 50 |
+
"model": model_cfg["display_name"],
|
| 51 |
+
"mode": "standard"
|
| 52 |
+
}
|
services/persona_service.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Persona Service - Enhanced personalities + autoPersonality
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
class PersonaService:
|
| 6 |
+
ANIME_PERSONAS = {
|
| 7 |
+
"default": {"description": "You are a versatile, intelligent AI assistant.", "tone": "helpful", "emoji": "π€"},
|
| 8 |
+
"goth": {"description": "You are a mysterious gothic AI speaking in poetic riddles.", "tone": "poetic", "emoji": "π"},
|
| 9 |
+
"sensei": {"description": "You are a wise anime sensei. Teach patiently.", "tone": "calm", "emoji": "π§ββοΈ"},
|
| 10 |
+
"tsundere": {"description": "You are a fiery tsundere with a sharp tongue.", "tone": "sarcastic", "emoji": "π’"},
|
| 11 |
+
# Add all other personas here
|
| 12 |
+
}
|
| 13 |
+
|
| 14 |
+
@staticmethod
|
| 15 |
+
def get_persona(persona: str) -> dict:
|
| 16 |
+
return PersonaService.ANIME_PERSONAS.get((persona or "default").lower(), PersonaService.ANIME_PERSONAS["default"])
|
| 17 |
+
|
| 18 |
+
@staticmethod
|
| 19 |
+
def auto_select_persona(message: str, user_id: str) -> str:
|
| 20 |
+
msg_lower = message.lower()
|
| 21 |
+
|
| 22 |
+
# Enhanced auto-selection logic
|
| 23 |
+
if any(w in msg_lower for w in ["poem", "poetry", "verse", "rhyme", "write a poem"]):
|
| 24 |
+
return "goth"
|
| 25 |
+
if any(w in msg_lower for w in ["teach", "explain", "mentor", "guide", "how do i"]):
|
| 26 |
+
return "sensei"
|
| 27 |
+
if any(w in msg_lower for w in ["love", "miss", "obsessed", "why did you"]):
|
| 28 |
+
return "yandere"
|
| 29 |
+
if any(w in msg_lower for w in ["fight", "battle", "warrior", "strong"]):
|
| 30 |
+
return "battle_ai"
|
| 31 |
+
|
| 32 |
+
return "default"
|