Spaces:
Build error
Build error
File size: 22,419 Bytes
69596ec | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 | """
Enhanced Memory Manager for STELLA AI Assistant
Integrates Mem0 for advanced memory management with fallback mechanisms
"""
import os
import json
import time
import uuid
import logging
from pathlib import Path
from typing import Dict, List, Optional, Any, Union
from datetime import datetime
# 设置日志记录
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
try:
from mem0 import Memory, MemoryClient
MEM0_AVAILABLE = True
logger.info("✅ Mem0 library loaded successfully")
except ImportError as e:
MEM0_AVAILABLE = False
logger.warning(f"⚠️ Mem0 library not available: {e}")
logger.info("💡 Install with: pip install mem0ai")
# Import traditional KnowledgeBase for fallback
from Knowledge_base import KnowledgeBase
# --- Base Memory Component ---
class BaseMemoryComponent:
"""所有记忆组件的基类"""
def __init__(self, component_name: str, gemini_model=None, mem0_config=None):
self.component_name = component_name
self.gemini_model = gemini_model
self.mem0_config = mem0_config
self.memory = None
self.mem0_enabled = False
# 初始化 Mem0
if MEM0_AVAILABLE and mem0_config:
try:
logger.info(f"🔧 正在初始化 {self.component_name} 的 Mem0 组件...")
if mem0_config.get('use_platform', False):
# 使用托管平台
self.memory = MemoryClient(api_key=mem0_config.get('api_key'))
else:
# 使用自托管版本,带有重试机制
config = self._get_component_config()
self.memory = Memory.from_config(config)
self.mem0_enabled = True
logger.info(f"✅ {self.component_name} Mem0 初始化成功")
except Exception as e:
logger.error(f"❌ {self.component_name} Mem0 初始化失败: {e}")
logger.info(f"📋 {self.component_name} 将使用传统知识库作为备用方案")
self.mem0_enabled = False
self.memory = None
def _get_component_config(self):
"""获取组件特定的 Mem0 配置"""
# 优先使用更新的 embedding 模型,如果不可用则使用备用方案
embedding_models = [
"text-embedding-3-small",
"text-embedding-3-large",
"nomic-embed-text" # 开源备用选项
]
base_config = {
"embedder": {
"provider": "openai",
"config": {
"model": embedding_models[0], # 使用第一个可用的模型
"api_key": self.mem0_config.get('openrouter_api_key'),
"openai_base_url": "https://openrouter.ai/api/v1"
}
},
"llm": {
"provider": "openai",
"config": {
"model": "gpt-4o-mini",
"api_key": self.mem0_config.get('openrouter_api_key'),
"openai_base_url": "https://openrouter.ai/api/v1"
}
},
"vector_store": {
"provider": "chroma",
"config": {
"collection_name": f"stella_{self.component_name}",
"path": f"/home/ubuntu/agent_outputs/mem0_db/{self.component_name}"
}
}
}
return base_config
# --- 1. Knowledge Base Component ---
class KnowledgeMemory(BaseMemoryComponent):
"""专门管理思维模板和解题经验的记忆组件"""
def __init__(self, gemini_model=None, mem0_config=None):
super().__init__("knowledge", gemini_model, mem0_config)
self.fallback_kb = None
# 如果 Mem0 不可用,初始化传统知识库
if not self.mem0_enabled:
self.fallback_kb = KnowledgeBase(gemini_model=gemini_model)
def add_template(self, task_description: str, thought_process: str, solution_outcome: str,
domain: str = "general", user_id: str = "agent_team"):
"""添加成功的思维模板"""
if self.mem0_enabled:
try:
conversation = [
{"role": "user", "content": f"Task: {task_description}"},
{"role": "assistant", "content": f"Reasoning: {thought_process}"},
{"role": "user", "content": f"Outcome: {solution_outcome}"}
]
metadata = {
"type": "problem_solving_template",
"domain": domain,
"timestamp": time.strftime("%Y-%m-%d %H:%M:%S"),
"keywords": self._extract_keywords(task_description)
}
result = self.memory.add(conversation, user_id=user_id, metadata=metadata)
print(f"💾 KnowledgeMemory: 成功保存思维模板")
return {"success": True, "memory_id": result.get('id', '')}
except Exception as e:
print(f"⚠️ KnowledgeMemory 保存失败: {str(e)}")
if self.fallback_kb:
return self.fallback_kb.add_template(task_description, thought_process, solution_outcome, domain)
else:
if self.fallback_kb:
return self.fallback_kb.add_template(task_description, thought_process, solution_outcome, domain)
return {"success": False, "message": "No available backend"}
def search_templates(self, task_description: str, top_k: int = 3, user_id: str = "agent_team"):
"""搜索相似的思维模板"""
if self.mem0_enabled:
try:
results = self.memory.search(
query=task_description,
user_id=user_id,
limit=top_k
)
templates = []
for result in results.get('results', []):
template = {
'task': task_description,
'key_reasoning': result.get('memory', ''),
'domain': result.get('metadata', {}).get('domain', 'general'),
'keywords': result.get('metadata', {}).get('keywords', []),
'timestamp': result.get('metadata', {}).get('timestamp', ''),
'similarity': result.get('score', 0.0),
'memory_id': result.get('id', '')
}
templates.append(template)
return {"success": True, "templates": templates}
except Exception as e:
print(f"⚠️ KnowledgeMemory 检索失败: {str(e)}")
if self.fallback_kb:
return {"success": True, "templates": self.fallback_kb.retrieve_similar_templates(task_description, top_k)}
else:
if self.fallback_kb:
return {"success": True, "templates": self.fallback_kb.retrieve_similar_templates(task_description, top_k)}
return {"success": False, "templates": []}
def get_stats(self, user_id: str = "agent_team"):
"""获取知识库统计信息"""
if self.mem0_enabled:
try:
# 获取用户的所有记忆
all_results = self.memory.search(
query="template problem solving",
user_id=user_id,
limit=1000 # 大数量来获取统计
)
return {
'component': 'KnowledgeMemory',
'backend': 'Mem0 Enhanced',
'total_templates': len(all_results.get('results', [])),
'user_id': user_id
}
except Exception as e:
return {
'component': 'KnowledgeMemory',
'backend': 'Error',
'total_templates': 0,
'error': str(e)
}
else:
if self.fallback_kb:
return {
'component': 'KnowledgeMemory',
'backend': 'Traditional KnowledgeBase',
'total_templates': len(self.fallback_kb.templates),
'user_id': user_id
}
return {
'component': 'KnowledgeMemory',
'backend': 'No backend',
'total_templates': 0
}
def _extract_keywords(self, text):
"""提取关键词"""
if self.fallback_kb:
return self.fallback_kb.extract_keywords(text)
else:
# 简单的关键词提取
return [word.lower() for word in text.split() if len(word) > 3]
# --- 2. Collaboration Memory Component ---
class CollaborationMemory(BaseMemoryComponent):
"""专门管理多智能体协作记忆的组件"""
def __init__(self, gemini_model=None, mem0_config=None):
super().__init__("collaboration", gemini_model, mem0_config)
def create_workspace(self, workspace_id: str, task_description: str,
participating_agents: list = None):
"""创建智能体团队的共享工作空间"""
if not self.mem0_enabled:
return {"success": False, "message": "Mem0 not available for collaboration"}
try:
participating_agents = participating_agents or ["dev_agent", "manager_agent", "critic_agent"]
workspace_memory = [{
"role": "system",
"content": f"Shared workspace '{workspace_id}' created for collaborative task"
}, {
"role": "assistant",
"content": f"Task: {task_description}\nParticipating agents: {', '.join(participating_agents)}"
}]
metadata = {
"type": "workspace_creation",
"workspace_id": workspace_id,
"task_description": task_description,
"participating_agents": participating_agents,
"status": "active",
"timestamp": time.strftime("%Y-%m-%d %H:%M:%S")
}
result = self.memory.add(workspace_memory, user_id="shared_workspace", metadata=metadata)
return {
"success": True,
"workspace_id": workspace_id,
"memory_id": result.get('id', ''),
"participating_agents": participating_agents
}
except Exception as e:
return {"success": False, "message": f"Error creating workspace: {str(e)}"}
def add_agent_observation(self, workspace_id: str, agent_name: str, content: str,
observation_type: str = "discovery"):
"""智能体添加观察或发现到共享工作空间"""
if not self.mem0_enabled:
return {"success": False, "message": "Mem0 not available"}
try:
memory_entry = [{
"role": "user",
"content": f"Agent: {agent_name}"
}, {
"role": "assistant",
"content": content
}]
metadata = {
"type": "agent_observation",
"observation_type": observation_type, # discovery, result, question, insight
"workspace_id": workspace_id,
"agent_name": agent_name,
"timestamp": time.strftime("%Y-%m-%d %H:%M:%S")
}
result = self.memory.add(memory_entry, user_id="shared_workspace", metadata=metadata)
return {
"success": True,
"memory_id": result.get('id', ''),
"workspace_id": workspace_id,
"agent_name": agent_name
}
except Exception as e:
return {"success": False, "message": f"Error adding observation: {str(e)}"}
def get_workspace_context(self, workspace_id: str, agent_perspective: str = "all",
limit: int = 20):
"""获取工作空间的协作上下文"""
if not self.mem0_enabled:
return {"success": False, "observations": []}
try:
# 搜索特定工作空间的记忆
results = self.memory.search(
query=f"workspace {workspace_id}",
user_id="shared_workspace",
limit=limit * 2
)
# 过滤和组织观察
observations = []
for result in results.get('results', []):
metadata = result.get('metadata', {})
if metadata.get('workspace_id') == workspace_id:
if agent_perspective == "all" or metadata.get('agent_name') == agent_perspective:
observations.append({
"memory_id": result.get('id', ''),
"agent_name": metadata.get('agent_name', ''),
"content": result.get('memory', ''),
"observation_type": metadata.get('observation_type', ''),
"timestamp": metadata.get('timestamp', ''),
"score": result.get('score', 0.0)
})
# 按时间排序
observations.sort(
key=lambda x: x.get('timestamp', ''),
reverse=True
)
return {
"success": True,
"workspace_id": workspace_id,
"observations": observations[:limit],
"total_found": len(observations)
}
except Exception as e:
return {"success": False, "observations": [], "message": str(e)}
def get_agent_contributions(self, workspace_id: str, agent_name: str, limit: int = 10):
"""获取特定智能体在工作空间的贡献"""
context = self.get_workspace_context(workspace_id, agent_name, limit)
if context["success"]:
return {
"success": True,
"agent_name": agent_name,
"workspace_id": workspace_id,
"contributions": context["observations"]
}
return {"success": False, "contributions": []}
# --- 3. Session Memory Component ---
class SessionMemory(BaseMemoryComponent):
"""专门管理多轮对话上下文的记忆组件"""
def __init__(self, gemini_model=None, mem0_config=None):
super().__init__("session", gemini_model, mem0_config)
def start_session(self, session_id: str, user_id: str, initial_context: str = ""):
"""开始新的会话"""
if not self.mem0_enabled:
return {"success": False, "message": "Mem0 not available for sessions"}
try:
session_start = [{
"role": "system",
"content": f"Session {session_id} started"
}, {
"role": "assistant",
"content": f"Initial context: {initial_context}"
}]
metadata = {
"type": "session_start",
"session_id": session_id,
"timestamp": time.strftime("%Y-%m-%d %H:%M:%S"),
"status": "active"
}
result = self.memory.add(session_start, user_id=user_id, metadata=metadata)
return {
"success": True,
"session_id": session_id,
"memory_id": result.get('id', '')
}
except Exception as e:
return {"success": False, "message": f"Error starting session: {str(e)}"}
def add_conversation_turn(self, session_id: str, user_id: str, user_message: str,
assistant_response: str, turn_type: str = "normal"):
"""添加对话轮次"""
if not self.mem0_enabled:
return {"success": False, "message": "Mem0 not available"}
try:
conversation_turn = [{
"role": "user",
"content": user_message
}, {
"role": "assistant",
"content": assistant_response
}]
metadata = {
"type": "conversation_turn",
"turn_type": turn_type, # normal, task_step, question, result
"session_id": session_id,
"timestamp": time.strftime("%Y-%m-%d %H:%M:%S")
}
result = self.memory.add(conversation_turn, user_id=user_id, metadata=metadata)
return {
"success": True,
"memory_id": result.get('id', ''),
"session_id": session_id
}
except Exception as e:
return {"success": False, "message": f"Error adding turn: {str(e)}"}
def get_session_context(self, session_id: str, user_id: str, limit: int = 10):
"""获取会话上下文"""
if not self.mem0_enabled:
return {"success": False, "context": []}
try:
# 搜索特定会话的记忆
results = self.memory.search(
query=f"session {session_id}",
user_id=user_id,
limit=limit * 2
)
# 过滤和组织会话上下文
context = []
for result in results.get('results', []):
metadata = result.get('metadata', {})
if metadata.get('session_id') == session_id:
context.append({
"memory_id": result.get('id', ''),
"content": result.get('memory', ''),
"turn_type": metadata.get('turn_type', 'normal'),
"timestamp": metadata.get('timestamp', ''),
"score": result.get('score', 0.0)
})
# 按时间排序
context.sort(key=lambda x: x.get('timestamp', ''))
return {
"success": True,
"session_id": session_id,
"context": context[:limit],
"total_turns": len(context)
}
except Exception as e:
return {"success": False, "context": [], "message": str(e)}
def get_user_preferences(self, user_id: str):
"""获取用户偏好和历史行为模式"""
if not self.mem0_enabled:
return {"success": False, "preferences": {}}
try:
# 搜索用户的所有会话记忆
results = self.memory.search(
query="conversation preference pattern",
user_id=user_id,
limit=50
)
# 分析偏好(简单实现)
preferences = {
"total_sessions": len(results.get('results', [])),
"common_topics": [],
"interaction_style": "standard"
}
return {
"success": True,
"user_id": user_id,
"preferences": preferences
}
except Exception as e:
return {"success": False, "preferences": {}, "message": str(e)}
# --- Main Memory Manager ---
class MemoryManager:
"""统一的内存管理器 - 协调所有记忆组件"""
def __init__(self, gemini_model=None, use_mem0=False, mem0_platform=False,
mem0_api_key=None, openrouter_api_key=None):
self.gemini_model = gemini_model
self.mem0_config = {
'use_platform': mem0_platform,
'api_key': mem0_api_key,
'openrouter_api_key': openrouter_api_key
} if use_mem0 else None
# 初始化各个记忆组件
print("🧠 初始化统一内存管理系统...")
self.knowledge = KnowledgeMemory(gemini_model, self.mem0_config)
self.collaboration = CollaborationMemory(gemini_model, self.mem0_config)
self.session = SessionMemory(gemini_model, self.mem0_config)
print("✅ MemoryManager 初始化完成")
self._print_stats()
def _print_stats(self):
"""打印各组件状态"""
knowledge_stats = self.knowledge.get_stats()
print(f"📚 知识记忆: {knowledge_stats['backend']} - {knowledge_stats['total_templates']} 个模板")
if self.collaboration.mem0_enabled:
print(f"🤝 协作记忆: Mem0 Enhanced - 已启用")
else:
print(f"🤝 协作记忆: 不可用")
if self.session.mem0_enabled:
print(f"💬 会话记忆: Mem0 Enhanced - 已启用")
else:
print(f"💬 会话记忆: 不可用")
def get_overall_stats(self):
"""获取整体统计信息"""
return {
"knowledge": self.knowledge.get_stats(),
"collaboration_enabled": self.collaboration.mem0_enabled,
"session_enabled": self.session.mem0_enabled,
"manager_version": "v1.0"
}
# --- 便捷方法用于向后兼容 ---
def add_template(self, *args, **kwargs):
"""向后兼容的模板添加方法"""
return self.knowledge.add_template(*args, **kwargs)
def retrieve_similar_templates(self, *args, **kwargs):
"""向后兼容的模板检索方法"""
result = self.knowledge.search_templates(*args, **kwargs)
return result.get('templates', []) if result['success'] else []
def get_memory_stats(self, *args, **kwargs):
"""向后兼容的统计方法"""
return self.knowledge.get_stats(*args, **kwargs) |