JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
fix: 删除memory目录下的冗余文件和代码
hzx9910a0e5e933ae
diff --git a/jiuwenclaw/agentserver/memory/__init__.py b/jiuwenclaw/agentserver/memory/__init__.pyindex bb5913483c..d04ed5592f 100644--- a/jiuwenclaw/agentserver/memory/__init__.py+++ b/jiuwenclaw/agentserver/memory/__init__.py@@ -4,15 +4,10 @@from .types import (MemorySearchResult,- MemoryProviderStatus,- MemorySyncProgressUpdate,MemoryFileEntry,MemoryChunk,- SessionFileEntry,MemorySource,FileEntry,- FtsStatus,- VectorStatus,)from .manager import MemoryIndexManager, get_memory_manager, clear_memory_manager_cachefrom .config import (@@ -24,23 +19,6 @@ from .config import (DEFAULT_WORKSPACE_DIR,)from .embeddings import EmbeddingProvider, create_embedding_provider-from .summarizer import (- LLMClient,- ConversationCompactor,- SessionSummarizer,- compact_memory,- summarize_session,- format_messages_for_summary,-)-from .compaction import (- MessageStatus,- MessageRecord,- TokenEstimator,- MessageRepository,- ContextCompactionManager,- CONTEXT_COMPACT_THRESHOLD,- CONTEXT_COMPACT_KEEP_RECENT,-)from .internal import (estimate_tokens,ensure_dir,@@ -48,7 +26,6 @@ from .internal import (build_file_entry,chunk_markdown,hash_text,- parse_embedding,build_fts_query,bm25_rank_to_score,is_memory_path,@@ -63,21 +40,15 @@ __all__ = ["EmbeddingProvider","create_embedding_provider","MemorySearchResult",- "MemoryProviderStatus",- "MemorySyncProgressUpdate","MemoryFileEntry","MemoryChunk",- "SessionFileEntry","MemorySource","FileEntry",- "FtsStatus",- "VectorStatus","ensure_dir","list_memory_files","build_file_entry","chunk_markdown","hash_text",- "parse_embedding","build_fts_query","bm25_rank_to_score","is_memory_path",@@ -87,18 +58,5 @@ __all__ = ["get_memory_mode","get_embed_config","DEFAULT_WORKSPACE_DIR",- "LLMClient",- "ConversationCompactor",- "SessionSummarizer",- "compact_memory",- "summarize_session",- "format_messages_for_summary",- "MessageStatus",- "MessageRecord",- "TokenEstimator",- "MessageRepository",- "ContextCompactionManager",- "CONTEXT_COMPACT_THRESHOLD",- "CONTEXT_COMPACT_KEEP_RECENT","estimate_tokens",]diff --git a/jiuwenclaw/agentserver/memory/compaction.py b/jiuwenclaw/agentserver/memory/compaction.pydeleted file mode 100644index ad3dcbed08..0000000000--- a/jiuwenclaw/agentserver/memory/compaction.py+++ /dev/null@@ -1,333 +0,0 @@-# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.--"""Context Compression Manager - Automatic message compression and summarization.--Provides automatic triggering of message compression when token threshold is exceeded.-"""--import asyncio-import json-import logging-import os-from enum import Enum-from typing import List, Dict, Any, Optional-from dataclasses import dataclass, field-from datetime import datetime--from .internal import estimate_tokens--logger = logging.getLogger(__name__)--CONTEXT_COMPACT_THRESHOLD = 8000-CONTEXT_COMPACT_KEEP_RECENT = 10-COMPRESSED_SUMMARY_FILE = "compressed_summary.json"---class MessageStatus(Enum):- """Message compression status marks."""- PENDING = "pending"- ARCHIVED = "archived"---@dataclass-class MessageRecord:- """Message with compression tracking."""- msg_id: str- role: str- content: str- created_at: str = ""- status: MessageStatus = MessageStatus.PENDING-- def to_dict(self) -> Dict[str, Any]:- return {- "msg_id": self.msg_id,- "role": self.role,- "content": self.content,- "created_at": self.created_at,- "status": self.status.value- }-- @classmethod- def from_dict(cls, data: Dict[str, Any]) -> "MessageRecord":- return cls(- msg_id=data["msg_id"],- role=data["role"],- content=data["content"],- created_at=data.get("created_at", ""),- status=MessageStatus(data.get("status", "pending"))- )---class TokenEstimator:- """Token estimator for messages using unified estimate_tokens."""-- @classmethod- def estimate_text(cls, text: str) -> int:- return estimate_tokens(text)-- @classmethod- def estimate_message(cls, message: Dict[str, Any]) -> int:- content = message.get("content", "")- if isinstance(content, str):- return cls.estimate_text(content)- elif isinstance(content, list):- total = 0- for block in content:- if isinstance(block, dict):- if block.get("type") == "text":- total += cls.estimate_text(block.get("text", ""))- elif block.get("type") == "tool_use":- total += cls.estimate_text(json.dumps(block.get("input", {})))- elif block.get("type") == "tool_result":- total += cls.estimate_text(str(block.get("output", "")))- return total- return 0-- @classmethod- def estimate_messages(cls, messages: List[Dict[str, Any]]) -> int:- return sum(cls.estimate_message(msg) for msg in messages)---class MessageRepository:- """Manages message storage with compression tracking."""-- def __init__(self, workspace_dir: str):- self.workspace_dir = workspace_dir- self.store_path = os.path.join(workspace_dir, "memory", "messages.json")- self.summary_path = os.path.join(workspace_dir, "memory", COMPRESSED_SUMMARY_FILE)- self._records: List[MessageRecord] = []- self._archived_summary: str = ""- self._load()-- def _load(self) -> None:- if os.path.exists(self.store_path):- try:- with open(self.store_path, "r", encoding="utf-8") as f:- data = json.load(f)- self._records = [MessageRecord.from_dict(m) for m in data.get("records", [])]- except Exception as e:- logger.warning(f"Failed to load messages: {e}")-- if os.path.exists(self.summary_path):- try:- with open(self.summary_path, "r", encoding="utf-8") as f:- data = json.load(f)- self._archived_summary = data.get("summary", "")- except Exception as e:- logger.warning(f"Failed to load compressed summary: {e}")-- def _save(self) -> None:- os.makedirs(os.path.dirname(self.store_path), exist_ok=True)-- with open(self.store_path, "w", encoding="utf-8") as f:- json.dump({- "records": [r.to_dict() for r in self._records]- }, f, ensure_ascii=False, indent=2)-- def _save_summary(self) -> None:- os.makedirs(os.path.dirname(self.summary_path), exist_ok=True)-- with open(self.summary_path, "w", encoding="utf-8") as f:- json.dump({- "summary": self._archived_summary,- "updated_at": datetime.now().isoformat()- }, f, ensure_ascii=False, indent=2)-- def add_record(self, role: str, content: str, msg_id: Optional[str] = None) -> MessageRecord:- import uuid-- record = MessageRecord(- msg_id=msg_id or str(uuid.uuid4()),- role=role,- content=content,- created_at=datetime.now().isoformat(),- status=MessageStatus.PENDING- )- self._records.append(record)- self._save()- return record-- def get_records(- self,- exclude_status: Optional[MessageStatus] = None,- include_status: Optional[MessageStatus] = None,- prepend_summary: bool = True- ) -> List[Dict[str, Any]]:- result = []-- if prepend_summary and self._archived_summary:- result.append({- "role": "system",- "content": self._archived_summary- })-- for rec in self._records:- if exclude_status and rec.status == exclude_status:- continue- if include_status and rec.status != include_status:- continue-- result.append({- "id": rec.msg_id,- "role": rec.role,- "content": rec.content,- "timestamp": rec.created_at- })-- return result-- def get_pending_records(self) -> List[MessageRecord]:- return [r for r in self._records if r.status == MessageStatus.PENDING]-- def update_archived_summary(self, summary: str) -> None:- self._archived_summary = summary- self._save_summary()- logger.info("Updated archived summary")-- def get_archived_summary(self) -> str:- return self._archived_summary-- def mark_records(self, msg_ids: List[str], status: MessageStatus) -> int:- count = 0- for rec in self._records:- if rec.msg_id in msg_ids:- rec.status = status- count += 1- self._save()- return count-- def clear(self) -> None:- self._records = []- self._archived_summary = ""- self._save()- self._save_summary()-- @property- def record_count(self) -> int:- return len(self._records)-- @property- def pending_count(self) -> int:- return len(self.get_pending_records())---class ContextCompactionManager:- """Manages automatic message compression."""-- def __init__(- self,- workspace_dir: str,- threshold: int = CONTEXT_COMPACT_THRESHOLD,- keep_recent: int = CONTEXT_COMPACT_KEEP_RECENT- ):- self.workspace_dir = workspace_dir- self.threshold = threshold- self.keep_recent = keep_recent- self.message_repo = MessageRepository(workspace_dir)- self._compaction_callbacks: List = []-- def add_compaction_callback(self, callback) -> None:- self._compaction_callbacks.append(callback)-- async def _notify_compaction(self, summary: str, archived_count: int) -> None:- for callback in self._compaction_callbacks:- try:- if asyncio.iscoroutinefunction(callback):- await callback(summary, archived_count)- else:- callback(summary, archived_count)- except Exception as e:- logger.error(f"Compaction callback failed: {e}")-- def should_compact(self, messages: List[Dict[str, Any]]) -> bool:- if len(messages) <= self.keep_recent:- return False-- messages_to_archive = messages[:-self.keep_recent] if self.keep_recent > 0 else messages- estimated_tokens = TokenEstimator.estimate_messages(messages_to_archive)-- return estimated_tokens > self.threshold-- async def check_and_compact(self, memory_manager) -> Optional[str]:- messages = self.message_repo.get_records(- exclude_status=MessageStatus.ARCHIVED,- prepend_summary=False- )-- if not self.should_compact(messages):- return None-- return await self.do_compact(memory_manager)-- async def do_compact(self, memory_manager) -> str:- records = self.message_repo.get_pending_records()-- if len(records) <= self.keep_recent:- logger.debug("Not enough messages to compact")- return ""-- records_to_archive = records[:-self.keep_recent] if self.keep_recent > 0 else records- records_to_keep = records[-self.keep_recent:] if self.keep_recent > 0 else []-- archive_dicts = [{- "role": r.role,- "content": r.content,- "timestamp": r.created_at- } for r in records_to_archive]-- estimated_tokens = TokenEstimator.estimate_messages(archive_dicts)-- logger.info(- "Context compaction triggered: estimated %d tokens "- "(threshold: %d), archivable_records: %d, keep_recent_records: %d",- estimated_tokens,- self.threshold,- len(records_to_archive),- len(records_to_keep)- )-- prior_summary = self.message_repo.get_archived_summary()-- from .summarizer import compact_memory- archived = await compact_memory(- messages=archive_dicts,- prior_summary=prior_summary- )-- self.message_repo.update_archived_summary(archived)-- archived_ids = [r.msg_id for r in records_to_archive]- marked_count = self.message_repo.mark_records(archived_ids, MessageStatus.ARCHIVED)-- logger.info(f"Marked {marked_count} messages as archived")-- memory_manager.add_async_summary_task(- messages=archive_dicts,- date=datetime.now().strftime("%Y-%m-%d")- )-- await self._notify_compaction(archived, len(records_to_archive))-- return archived-- def add_message(self, role: str, content: str) -> MessageRecord:- return self.message_repo.add_record(role, content)-- def get_messages_for_context(self) -> List[Dict[str, Any]]:- return self.message_repo.get_records(- exclude_status=MessageStatus.ARCHIVED,- prepend_summary=True- )-- def get_archived_summary(self) -> str:- return self.message_repo.get_archived_summary()-- @property- def stats(self) -> Dict[str, Any]:- return {- "total_records": self.message_repo.record_count,- "pending_records": self.message_repo.pending_count,- "threshold": self.threshold,- "keep_recent": self.keep_recent,- "has_archived_summary": bool(self.message_repo.get_archived_summary())- }diff --git a/jiuwenclaw/agentserver/memory/manager.py b/jiuwenclaw/agentserver/memory/manager.pyindex 6faffbd499..675679387e 100644--- a/jiuwenclaw/agentserver/memory/manager.py+++ b/jiuwenclaw/agentserver/memory/manager.py@@ -11,7 +11,6 @@ import asyncioimport datetimefrom typing import List, Optional, Dict, Any, Setfrom dataclasses import dataclass-from pathlib import Pathfrom .types import (MemorySearchResult, MemoryFileEntry, MemoryChunk, MemorySource@@ -100,7 +99,6 @@ class MemoryIndexManager:self._event_loop: Optional[asyncio.AbstractEventLoop] = Noneself._watcher_initialized: bool = Falseself._file_stability_tracker: Dict[str, float] = {}- self._summary_tasks: List[asyncio.Task] = []@classmethodasync def get(@@ -1180,120 +1178,6 @@ class MemoryIndexManager:except:return 0- async def compact_memory(- self,- messages: List[Dict[str, Any]],- prior_summary: str = ""- ) -> str:- """Compact messages into a summary.-- Args:- messages: List of messages to compact- prior_summary: Prior summary to build upon-- Returns:- Compacted summary- """- from .summarizer import ConversationCompactor-- compactor = ConversationCompactor()- return await compactor.compact(messages, prior_summary)-- async def summary_memory(- self,- messages: List[Dict[str, Any]],- date: Optional[str] = None- ) -> str:- """Generate a session summary.-- Args:- messages: List of messages to summarize- date: Date string (YYYY-MM-DD)-- Returns:- Session summary- """- from .summarizer import SessionSummarizer-- summarizer = SessionSummarizer()- summary = await summarizer.summarize(messages, date)-- if summary:- today = date or datetime.datetime.now().strftime("%Y-%m-%d")- summary_file = os.path.join(self.workspace_dir, "memory", f"{today}-summary.md")-- os.makedirs(os.path.dirname(summary_file), exist_ok=True)- with open(summary_file, "w", encoding="utf-8") as f:- f.write(f"# Session Summary - {today}\n\n{summary}")-- logger.info(f"Session summary saved to: {summary_file}")-- return summary-- def add_async_summary_task(- self,- messages: List[Dict[str, Any]],- date: Optional[str] = None- ):- """Add an async task to generate session summary.-- Cleans up completed tasks before adding new one.- Tracks all tasks for proper lifecycle management.-- Args:- messages: List of messages to summarize- date: Date string (YYYY-MM-DD)- """- self._cleanup_summary_tasks()-- async def _run_summary():- try:- result = await self.summary_memory(messages, date)- logger.info(f"Summary task completed: {date or 'today'}")- return result- except Exception as e:- logger.error(f"Async summary task failed: {e}")- raise-- task = asyncio.create_task(_run_summary())- self._summary_tasks.append(task)- logger.debug(f"Added summary task for {date or 'today'}, total tasks: {len(self._summary_tasks)}")-- def _cleanup_summary_tasks(self) -> None:- """Clean up completed summary tasks.-- Removes completed tasks from the list and logs any exceptions.- """- remaining_tasks = []- for task in self._summary_tasks:- if task.done():- exc = task.exception()- if exc is not None:- logger.error(f"Summary task failed with exception: {exc}")- else:- try:- result = task.result()- logger.debug(f"Summary task completed successfully")- except Exception as e:- logger.error(f"Summary task result retrieval failed: {e}")- else:- remaining_tasks.append(task)-- if len(remaining_tasks) != len(self._summary_tasks):- cleaned = len(self._summary_tasks) - len(remaining_tasks)- logger.debug(f"Cleaned up {cleaned} completed summary tasks")-- self._summary_tasks = remaining_tasks-- def get_pending_summary_tasks(self) -> int:- """Get count of pending summary tasks.-- Returns:- Number of pending (not completed) summary tasks- """- self._cleanup_summary_tasks()- return len(self._summary_tasks)-async def close(self) -> None:"""Close the memory manager."""if self.closed:@@ -1308,21 +1192,6 @@ class MemoryIndexManager:if self._session_timer:self._session_timer.cancel()- self._cleanup_summary_tasks()- if self._summary_tasks:- logger.info(f"Waiting for {len(self._summary_tasks)} pending summary tasks...")- try:- done, pending = await asyncio.wait(- self._summary_tasks,- timeout=30.0- )- if pending:- logger.warning(f"Cancelling {len(pending)} pending summary tasks")- for task in pending:- task.cancel()- except Exception as e:- logger.warning(f"Error waiting for summary tasks: {e}")-if self._file_observer:try:self._file_observer.stop()diff --git a/jiuwenclaw/agentserver/memory/summarizer.py b/jiuwenclaw/agentserver/memory/summarizer.pydeleted file mode 100644index f2e8d5a649..0000000000--- a/jiuwenclaw/agentserver/memory/summarizer.py+++ /dev/null@@ -1,293 +0,0 @@-# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.--"""LLM-based memory compression and summarization for JiuWenClaw."""--import logging-import os-import datetime-from typing import List, Dict, Any, Optional-from pathlib import Path--from openjiuwen.core.foundation.llm import Model-from openjiuwen.core.foundation.llm.schema.config import ModelRequestConfig, ModelClientConfig--from jiuwenclaw.config import get_config--logger = logging.getLogger(__name__)---def format_messages_for_summary(- messages: List[Dict[str, Any]],- include_timestamp: bool = False,- max_content_length: int = 1000-) -> str:- """Format messages into conversation string for summarization.-- Args:- messages: List of message dicts- include_timestamp: Whether to include timestamps- max_content_length: Max length for content truncation-- Returns:- Formatted conversation string- """- lines = []- for msg in messages:- role = msg.get("role", "unknown")- content = msg.get("content", "")-- if isinstance(content, list):- text_parts = []- for block in content:- if isinstance(block, dict):- if block.get("type") == "text":- text_parts.append(block.get("text", ""))- elif block.get("type") == "tool_use":- text_parts.append(f"[Tool: {block.get('name', 'unknown')}]")- elif block.get("type") == "tool_result":- text_parts.append(f"[Tool Result: {str(block.get('output', ''))[:200]}]")- else:- text_parts.append(str(block))- content = " ".join(text_parts)-- if include_timestamp:- timestamp = msg.get("time_created", "") or msg.get("timestamp", "")- time_prefix = f"[{timestamp}] " if timestamp else ""- else:- time_prefix = ""-- if len(content) > max_content_length:- content = content[:max_content_length] + "..."-- if role == "user":- lines.append(f"{time_prefix}User: {content}")- elif role == "assistant":- lines.append(f"{time_prefix}Assistant: {content}")- elif role == "system":- lines.append(f"{time_prefix}System: {content}")- elif role == "tool":- lines.append(f"{time_prefix}Tool Result: {content[:500]}")-- return "\n".join(lines)---class LLMClient:- """LLM client using openjiuwen framework."""-- def __init__(self):- self._load_config()-- def _load_config(self):- """Load LLM configuration from config.yaml."""- config = get_config()-- react_config = config.get("react", {})- model_client_config = react_config.get("model_client_config", {})-- self.api_key = model_client_config.get("api_key", "")- self.base_url = model_client_config.get("api_base", "")- self.model_name = react_config.get("model_name", "")- self.model_provider = model_client_config.get("client_provider", "OpenAI")- self.verify_ssl = model_client_config.get("verify_ssl", False)-- if self.base_url.endswith("/chat/completions"):- self.base_url = self.base_url.rsplit("/chat/completions", 1)[0]-- async def chat(self, messages: List[Dict[str, str]], temperature: float = 0.3) -> str:- """Call LLM with messages using openJiuwen's Model.-- Args:- messages: List of message dicts with role and content- temperature: Temperature for generation-- Returns:- Generated text- """-- if not self.api_key:- raise ValueError("LLM API key not configured")-- model_config = ModelRequestConfig(- model=self.model_name,- temperature=temperature- )-- model_client_config = ModelClientConfig(- client_id="1",- client_provider=self.model_provider,- api_key=self.api_key,- api_base=self.base_url,- verify_ssl=self.verify_ssl- )-- llm = Model(model_config=model_config, model_client_config=model_client_config)-- formatted_messages = []- for msg in messages:- formatted_messages.append({- "role": msg["role"],- "content": msg["content"]- })-- response = await llm.invoke(formatted_messages)-- if hasattr(response, 'content'):- return response.content- elif isinstance(response, dict):- return response.get('content', str(response))- else:- return str(response)---class ConversationCompactor:- """Compacts conversation messages into summaries."""-- COMPACT_PROMPT = """你是一个对话压缩助手。请将以下对话历史压缩为简洁的摘要。--要求:-1. 保留关键信息和决策-2. 保留用户的重要偏好和习惯-3. 保留待办事项和提醒-4. 省略不必要的闲聊和重复内容-5. 使用简洁的语言--对话历史:-{conversation}--请输出压缩后的摘要(不要输出其他内容):"""-- def __init__(self, llm_client: Optional[LLMClient] = None):- self.llm = llm_client or LLMClient()-- async def compact(- self,- messages: List[Dict[str, Any]],- prior_summary: str = ""- ) -> str:- """Compact messages into a summary.-- Args:- messages: List of messages to compact- prior_summary: Prior summary to build upon-- Returns:- Compacted summary- """- if not messages:- return prior_summary-- conversation = format_messages_for_summary(messages, include_timestamp=False)-- if prior_summary:- conversation = f"[Prior Summary]\n{prior_summary}\n\n[New Conversation]\n{conversation}"-- full_prompt = self.COMPACT_PROMPT.format(conversation=conversation)-- try:- summary = await self.llm.chat([- {"role": "user", "content": full_prompt}- ])-- return f"""<context-summary>-{summary.strip()}-</context-summary>-这是之前对话的摘要,请将其作为上下文以保持对话的连续性。"""-- except Exception as e:- logger.error(f"Compaction failed: {e}")- return prior_summary---class SessionSummarizer:- """Generates daily session summaries."""-- SUMMARY_PROMPT = """你是一个会话摘要助手。请为以下日期生成结构化的摘要。--日期:{date}--对话内容:-{conversation}--请按以下格式输出摘要:--## 今日重要事项-- [列出重要事件、决策、约定等]--## 用户偏好更新-- [列出新增表达的偏好或习惯]--## 待办事项-- [列出需要跟进的事项]--## 其他备注-- [其他值得记录的信息]--请输出摘要(不要输出其他内容):"""-- def __init__(self, llm_client: Optional[LLMClient] = None):- self.llm = llm_client or LLMClient()-- async def summarize(- self,- messages: List[Dict[str, Any]],- date: Optional[str] = None- ) -> str:- """Generate a summary of messages for a specific date.-- Args:- messages: List of messages to summarize- date: Date string (YYYY-MM-DD), defaults to today-- Returns:- Generated summary- """- if not messages:- return ""-- date = date or datetime.datetime.now().strftime("%Y-%m-%d")- conversation = format_messages_for_summary(messages, include_timestamp=True)-- full_prompt = self.SUMMARY_PROMPT.format(date=date, conversation=conversation)-- try:- summary = await self.llm.chat([- {"role": "user", "content": full_prompt}- ])- return summary.strip()- except Exception as e:- logger.error(f"Summarization failed: {e}")- return f"# Session Summary - {date}\n\nSummary generation failed, please check the conversation log manually."---async def compact_memory(- messages: List[Dict[str, Any]],- prior_summary: str = ""-) -> str:- """Compact messages into a summary.-- Args:- messages: List of messages to compact- prior_summary: Prior summary to build upon-- Returns:- Compacted summary- """- compactor = ConversationCompactor()- return await compactor.compact(messages, prior_summary)---async def summarize_session(- messages: List[Dict[str, Any]],- date: Optional[str] = None-) -> str:- """Generate a session summary.-- Args:- messages: List of messages to summarize- date: Date string (YYYY-MM-DD)-- Returns:- Session summary- """- summarizer = SessionSummarizer()- return await summarizer.summarize(messages, date)diff --git a/jiuwenclaw/agentserver/memory/types.py b/jiuwenclaw/agentserver/memory/types.pyindex a30905ae00..d4e4913efb 100644--- a/jiuwenclaw/agentserver/memory/types.py+++ b/jiuwenclaw/agentserver/memory/types.py@@ -2,8 +2,8 @@"""Memory system type definitions."""-from typing import List, Dict, Any, Optional, Literal, TypedDict-from dataclasses import dataclass, field+from typing import List, Dict, Any, Optional, Literal+from dataclasses import dataclassMemorySource = Literal["memory", "sessions"]