๐ซ CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org
Python agentai-societiesartificial-intelligencecommunicative-aicooperative-aideep-learninglarge-language-modelsmulti-agent-systemsnatural-language-processing
[feat] Markdown Agent Context Handling (#2934)
Hesam Sheikh1102515c5614
diff --git a/camel/agents/chat_agent.py b/camel/agents/chat_agent.pyindex 6c79e74f8..d7fffb240 100644--- a/camel/agents/chat_agent.py+++ b/camel/agents/chat_agent.py@@ -63,6 +63,7 @@ from camel.memories import (MemoryRecord,ScoreBasedContextCreator,)+from camel.memories.blocks.chat_history_block import EmptyMemoryWarningfrom camel.messages import (BaseMessage,FunctionCallingMessage,@@ -841,7 +842,12 @@ class ChatAgent(BaseAgent):current_tokens = token_counter.count_tokens_from_messages([message.to_openai_message(role)])- _, ctx_tokens = self.memory.get_context()+ import warnings++ with warnings.catch_warnings():+ warnings.filterwarnings("ignore", category=EmptyMemoryWarning)+ _, ctx_tokens = self.memory.get_context()+remaining_budget = max(0, token_limit - ctx_tokens)if current_tokens <= remaining_budget:@@ -1035,6 +1041,7 @@ class ChatAgent(BaseAgent):None"""self.memory.clear()+if self.system_message is not None:self.update_memory(self.system_message, OpenAIBackendRole.SYSTEM)diff --git a/camel/memories/__init__.py b/camel/memories/__init__.pyindex 44dbae405..f8b60fb45 100644--- a/camel/memories/__init__.py+++ b/camel/memories/__init__.py@@ -18,7 +18,7 @@ from .agent_memories import (VectorDBMemory,)from .base import AgentMemory, BaseContextCreator, MemoryBlock-from .blocks.chat_history_block import ChatHistoryBlock+from .blocks.chat_history_block import ChatHistoryBlock, EmptyMemoryWarningfrom .blocks.vectordb_block import VectorDBBlockfrom .context_creators.score_based import ScoreBasedContextCreatorfrom .records import ContextRecord, MemoryRecord@@ -35,4 +35,5 @@ __all__ = ['ChatHistoryBlock','VectorDBBlock','LongtermAgentMemory',+ 'EmptyMemoryWarning',]diff --git a/camel/memories/agent_memories.py b/camel/memories/agent_memories.pyindex 785aa724d..01abee68a 100644--- a/camel/memories/agent_memories.py+++ b/camel/memories/agent_memories.py@@ -51,7 +51,9 @@ class ChatHistoryMemory(AgentMemory):raise ValueError("`window_size` must be non-negative.")self._context_creator = context_creatorself._window_size = window_size- self._chat_history_block = ChatHistoryBlock(storage=storage)+ self._chat_history_block = ChatHistoryBlock(+ storage=storage,+ )self._agent_id = agent_id@propertydiff --git a/camel/memories/blocks/chat_history_block.py b/camel/memories/blocks/chat_history_block.pyindex bb0abb4ef..e0251c1e5 100644--- a/camel/memories/blocks/chat_history_block.py+++ b/camel/memories/blocks/chat_history_block.py@@ -21,6 +21,17 @@ from camel.storages.key_value_storages.in_memory import InMemoryKeyValueStoragefrom camel.types import OpenAIBackendRole+class EmptyMemoryWarning(UserWarning):+ """Warning raised when attempting to access an empty memory.++ This warning is raised when operations are performed on memory+ that contains no records. It can be safely caught and suppressed+ in contexts where empty memory is expected.+ """++ pass++class ChatHistoryBlock(MemoryBlock):r"""An implementation of the :obj:`MemoryBlock` abstract base class formaintaining a record of chat histories.@@ -39,7 +50,7 @@ class ChatHistoryBlock(MemoryBlock):last message is 1.0, and with each step taken backward, the scoreof the message is multiplied by the `keep_rate`. Higher `keep_rate`leads to high possibility to keep history messages during context- creation.+ creation. (default: :obj:`0.9`)"""def __init__(@@ -70,7 +81,11 @@ class ChatHistoryBlock(MemoryBlock):"""record_dicts = self.storage.load()if len(record_dicts) == 0:- warnings.warn("The `ChatHistoryMemory` is empty.")+ warnings.warn(+ "The `ChatHistoryMemory` is empty.",+ EmptyMemoryWarning,+ stacklevel=1,+ )return list()if window_size is not None and window_size >= 0:diff --git a/camel/toolkits/__init__.py b/camel/toolkits/__init__.pyindex 0255fbf2b..4bbe2b387 100644--- a/camel/toolkits/__init__.py+++ b/camel/toolkits/__init__.py@@ -88,6 +88,7 @@ from .message_agent_toolkit import AgentCommunicationToolkitfrom .web_deploy_toolkit import WebDeployToolkitfrom .screenshot_toolkit import ScreenshotToolkitfrom .message_integration import ToolkitMessageIntegration+from .context_summarizer_toolkit import ContextSummarizerToolkitfrom .notion_mcp_toolkit import NotionMCPToolkitfrom .vertex_ai_veo_toolkit import VertexAIVeoToolkitfrom .minimax_mcp_toolkit import MinimaxMCPToolkit@@ -168,6 +169,7 @@ __all__ = ['ScreenshotToolkit','RegisteredAgentToolkit','ToolkitMessageIntegration',+ 'ContextSummarizerToolkit','NotionMCPToolkit','VertexAIVeoToolkit','MinimaxMCPToolkit',diff --git a/camel/toolkits/context_summarizer_toolkit.py b/camel/toolkits/context_summarizer_toolkit.pynew file mode 100644index 000000000..299550093--- /dev/null+++ b/camel/toolkits/context_summarizer_toolkit.py@@ -0,0 +1,681 @@+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========++import glob+import os+from datetime import datetime+from pathlib import Path+from typing import TYPE_CHECKING, List, Optional++from camel.logger import get_logger+from camel.toolkits import FunctionTool+from camel.toolkits.base import BaseToolkit+from camel.utils.context_utils import ContextUtility++if TYPE_CHECKING:+ from camel.agents import ChatAgent+ from camel.memories.records import MemoryRecord++logger = get_logger(__name__)+++class ContextSummarizerToolkit(BaseToolkit):+ r"""A toolkit that provides intelligent context summarization and+ management for agents.++ This toolkit enables agents to compress conversation context through+ intelligent summarization, save conversation history to markdown files,+ and search through past conversations. It handles all context management+ needs in a single toolkit.++ Key features:+ - Intelligent context compression with over-compression prevention+ - Markdown file storage with session management+ - Simple text-based search through conversation history+ - Configurable summarization prompts+ - Context loading and saving capabilities+ """++ def __init__(+ self,+ agent: "ChatAgent",+ working_directory: Optional[str] = None,+ timeout: Optional[float] = None,+ summary_prompt_template: Optional[str] = None,+ ):+ r"""Initialize the ContextSummarizerToolkit.++ Args:+ agent (ChatAgent): The agent that is using the toolkit.+ This is required to access the agent's memory.+ working_directory (str, optional): The directory path where notes+ will be stored. If not provided, a default directory will be+ used.+ timeout (Optional[float]): The timeout for the toolkit.+ summary_prompt_template (Optional[str]): Custom prompt template+ for summarization. If None, a default task-focused template+ is used. Users can customize this for different use cases.+ """+ super().__init__(timeout=timeout)++ self.agent = agent+ self.working_directory_param = working_directory+ self.summary_prompt_template = summary_prompt_template++ # compression tracking to prevent over-compression+ self.compressed_message_uuids: set = set()+ self.compression_count = 0+ self.existing_summary: Optional[str] = ""++ # Create a separate agent for summarization without tools to avoid+ # circular calls+ self.summary_agent = ChatAgent(+ system_message="You are a helpful assistant that creates concise "+ "summaries of conversations.",+ model=self.agent.model_backend,+ agent_id=f"{self.agent.agent_id}_summarizer",+ )++ # Setup storage and file management using ContextUtility+ self._setup_storage(working_directory)++ def _setup_storage(self, working_directory: Optional[str]) -> None:+ r"""Initialize storage paths and create session-specific directories+ using ContextUtility for file management."""+ # Determine the base directory for context compression+ if working_directory:+ base_dir = working_directory+ else:+ camel_workdir = os.environ.get("CAMEL_WORKDIR")+ if camel_workdir:+ base_dir = str(Path(camel_workdir) / "context_compression")+ else:+ base_dir = "context_compression"++ # Initialize ContextUtility with the base directory+ self.context_util = ContextUtility(working_directory=base_dir)++ # Store references for compatibility+ self.working_directory = self.context_util.get_working_directory()+ self.session_id = self.context_util.get_session_id()++ # File names+ self.summary_filename = "agent_memory_summary"+ self.history_filename = "agent_memory_history"++ # ========= CORE COMPRESSION METHODS =========++ def _summarize_messages(+ self,+ memory_records: List["MemoryRecord"],+ ) -> str:+ r"""Generate a summary of the conversation context.++ Args:+ memory_records (List["MemoryRecord"]): A list of memory records to+ summarize.++ Returns:+ str: The summary of the conversation context.+ """+ if not memory_records:+ logger.warning(+ "No memory records provided. Returning existing summary."+ )+ return self.existing_summary or ""++ # check for over-compression prevention+ record_uuids = {record.uuid for record in memory_records}+ already_compressed = record_uuids.intersection(+ self.compressed_message_uuids+ )++ if already_compressed:+ logger.warning(+ f"Preventing over-compression: {len(already_compressed)} "+ f"records have already been compressed. Returning existing "+ f"summary."+ )+ return self.existing_summary or ""++ try:+ # 1. reset summary agent state for clean summarization+ self.summary_agent.reset()++ # 2. format the conversation+ conversation_text = self._format_conversation(memory_records)++ # 3. create the summary prompt+ summary_prompt = self._create_summary_prompt(conversation_text)++ # 4. generate summary using the agent+ response = self.summary_agent.step(summary_prompt)++ # 5. extract the summary from response and store+ summary_content = response.msgs[-1].content.strip()+ self.existing_summary = summary_content++ # 6. mark these records as compressed to prevent re-compression+ record_uuids = {record.uuid for record in memory_records}+ self.compressed_message_uuids.update(record_uuids)+ self.compression_count += 1++ logger.info(+ f"Successfully generated summary for {len(memory_records)} "+ f"messages. Compression count: {self.compression_count}"+ )+ return summary_content++ except Exception as e:+ logger.error(f"Error generating summary: {e}")+ return self.existing_summary or ""++ def _save_summary(self, summary: str) -> str:+ r"""Persist conversation summary to markdown file with metadata+ including timestamp and session information.++ Args:+ summary (str): The summary text to save.++ Returns:+ str: Success message or error message.+ """+ try:+ # prepare metadata for unified markdown saving+ timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')+ metadata = {+ 'Save Time': timestamp,+ 'Session ID': self.session_id,+ }++ # use ContextUtility's unified markdown saving+ return self.context_util.save_markdown_file(+ filename=self.summary_filename,+ content=f"## Summary\n\n{summary}\n",+ title=f"Conversation Summary: {self.session_id}",+ metadata=metadata,+ )+ except Exception as e:+ logger.error(f"Error saving summary: {e}")+ return f"Error saving summary: {e}"++ def _save_history(self, memory_records: List["MemoryRecord"]) -> str:+ r"""Export complete conversation transcript as formatted markdown+ with message roles, agent IDs, and content structure preserved.++ Args:+ memory_records (List["MemoryRecord"]): The list of memory records+ to save.++ Returns:+ str: Success message or error message.+ """+ try:+ # prepare metadata for markdown saving+ timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')+ metadata = {+ 'Save Time': timestamp,+ 'Total Messages': len(memory_records),+ 'Session ID': self.session_id,+ }++ # format the transcript for markdown+ transcript_content = "## Full Transcript\n\n"+ for i, record in enumerate(memory_records):+ message = record.message+ role = getattr(message, "role_name", "unknown")+ content = getattr(message, "content", str(message))+ agent_id = record.agent_id or "unknown"+ role_at_backend = (+ record.role_at_backend.value+ if hasattr(record.role_at_backend, 'value')+ else str(record.role_at_backend)+ )++ transcript_content += f"### Message {i + 1} - {role}\n"+ transcript_content += f"**Agent ID:** {agent_id} \n"+ transcript_content += (+ f"**Backend Role:** {role_at_backend} \n"+ )+ transcript_content += f"**Content:**\n```\n{content}\n```\n\n"+ transcript_content += "---\n\n"++ # use ContextUtility's markdown saving+ return self.context_util.save_markdown_file(+ filename=self.history_filename,+ content=transcript_content,+ title=f"Conversation History: {self.session_id}",+ metadata=metadata,+ )+ except Exception as e:+ logger.error(f"Error saving history: {e}")+ return f"Error saving history: {e}"++ def _compress_and_save(self, memory_records: List["MemoryRecord"]) -> str:+ r"""Complete compression pipeline: summarize and save both history and+ summary.++ Args:+ memory_records (List["MemoryRecord"]): The memory records to+ compress and save.++ Returns:+ str: The generated summary text.+ """+ try:+ # generate summary+ summary = self._summarize_messages(memory_records)++ # save both history and summary+ history_result = self._save_history(memory_records)+ summary_result = self._save_summary(summary)++ if "Error" not in history_result and "Error" not in summary_result:+ return summary+ else:+ error_msg = (+ f"Compression partially failed. History: {history_result},"+ f" Summary: {summary_result}"+ )+ logger.error(error_msg)+ raise Exception(error_msg)++ except Exception as e:+ logger.error(f"Error in compress_and_save: {e}")+ return self.existing_summary or ""++ # ========= FILE MANAGEMENT METHODS =========++ def _load_summary(self) -> str:+ r"""Retrieve previously saved conversation summary from disk+ for context restoration or continuation.++ Returns:+ str: The summary content, or empty string if not found.+ """+ return self.context_util.load_markdown_file(self.summary_filename)++ def _load_history(self) -> str:+ r"""Retrieve complete conversation transcript from saved markdown+ file including all message details and formatting.++ Returns:+ str: The history content, or empty string if not found.+ """+ return self.context_util.load_markdown_file(self.history_filename)++ # ========= PROMPT GENERATION METHODS =========++ def _format_conversation(+ self,+ memory_records: List["MemoryRecord"],+ ) -> str:+ r"""Convert memory records into human-readable conversation format+ with role names and message content for summarization processing.++ Args:+ memory_records (List["MemoryRecord"]): A list of memory records to+ format.++ Returns:+ str: The formatted conversation.+ """+ return self.context_util.format_memory_as_conversation(memory_records)++ def _create_summary_prompt(+ self,+ conversation_text: str,+ ) -> str:+ r"""Construct detailed summarization prompt with instructions+ for extracting key information, goals, and progress from conversation.++ Args:+ conversation_text (str): The formatted conversation to summarize.++ Returns:+ str: The complete prompt for summarization.+ """++ # use custom template if provided, otherwise use default+ if self.summary_prompt_template:+ base_prompt = self.summary_prompt_template+ else:+ base_prompt = """The following is a conversation history of a \+large language model agent.+Analyze it and extract the key information from it. The information will be+passed on to a new agent that will use it to understand the problem and \+continue working on it without having to start from scratch. Focus on:+- User's main goal (e.g. "The user wants my help with data analysis of \+customer sales data.")+- Key information about the user and their preferences (e.g. "The user is a \+student who prefers concise bullet-point responses.")+- Tasks that were accomplished (e.g. "I found the top 10 customers by total \+sales amounts, wrote a Python script to...")+- Tools and methods that were used **if tool/function calls have been made** \+(e.g. "I used CodeExecutionToolkit to execute a Python script to analyze the \+data.")+- Important discoveries or solutions found (e.g. "I found there are duplicate \+entries in the customer name column, which must be taken care of before \+proceeding with the analysis.")+- Technical approaches that worked **if the task is technical** (e.g. "Using \+Pandas + matplotlib seem to yield the best responses for the user's \+queries.)+Return only there summary with no preamble or extra words"""++ # if we want to extend an existing summary+ if self.existing_summary:+ base_prompt += f"""++Existing summary from before:+{self.existing_summary}++Provide an updated summary that incorporates both the previous work and the \+new conversation."""++ prompt = f"""{base_prompt}++Conversation:+{conversation_text}++Summary:"""+ return prompt++ # ========= PUBLIC TOOL INTERFACE METHODS =========++ def summarize_full_conversation_history(self) -> str:+ r"""Save the conversation history and generate an intelligent summary.++ This function should be used when the memory becomes cluttered with too+ many unrelated conversations or information that might be irrelevant to+ the core task. It will generate a summary and save both the summary+ and full conversation history to markdown files. Then it clears the+ memory and replaces it with the summary for a context refresh. The+ conversation must flow naturally from the summary.++ Returns:+ str: Success message with brief summary, or error message.+ """+ try:+ # Get memory records using ContextUtility+ memory_records = self.context_util.get_agent_memory_records(+ self.agent+ )+ message_count = len(memory_records)++ if message_count == 0:+ return "No conversation history found to save."++ # Use compression service directly to avoid tool calling loops+ summary = self._compress_and_save(memory_records)++ # empty memory and replace it with the summary+ self._refresh_context_with_summary(summary)++ logger.info(+ f"Context compression completed - {message_count} "+ f"messages processed"+ )++ return (+ "Full context summarized, summary added as system message, "+ "and full history removed."+ )++ except Exception as e:+ error_msg = f"Failed to save conversation memory: {e}"+ logger.error(error_msg)+ return error_msg++ def _refresh_context_with_summary(self, summary: str) -> bool:+ r"""Empty the agent's memory and replace it with a summary+ of the conversation history.++ Args:+ summary (str): The summary of the conversation history.++ Returns:+ bool: True if the context was refreshed successfully, False+ otherwise.+ """+ try:+ # clear the memory+ self.agent.clear_memory()++ # add summary as context+ if summary and summary.strip():+ from camel.messages import BaseMessage+ from camel.types import OpenAIBackendRole++ summary_message = BaseMessage.make_assistant_message(+ role_name="Assistant",+ content=f"[Context Summary]\n\n{summary}",+ )+ self.agent.update_memory(+ summary_message, OpenAIBackendRole.SYSTEM+ )+ return True+ return False++ except Exception as e:+ logger.error(+ f"Failed to empty memory and replace it with summary: {e}"+ )+ return False++ def get_conversation_memory_info(self) -> str:+ r"""Get information about the current conversation memory state+ and saved files. The information includes:+ - Number of messages in memory+ - Save directory+ - If summary and history files exist and how many+ characters they have++ Returns:+ str: Information about current memory and saved files.+ """+ try:+ # Current memory info using ContextUtility+ memory_records = self.context_util.get_agent_memory_records(+ self.agent+ )+ current_count = len(memory_records)++ info_msg = f"Current messages in memory: {current_count}\n"+ info_msg += f"Save directory: {self.working_directory}\n"++ # Check if saved files exist+ try:+ summary_content = self._load_summary()+ history_content = self._load_history()++ if summary_content.strip():+ info_msg += (+ f"Summary file: Available ({len(summary_content)} "+ f"chars)\n"+ )+ else:+ info_msg += "Summary file: Not found\n"++ if history_content.strip():+ info_msg += (+ f"History file: Available ({len(history_content)} "+ f"chars)\n"+ )+ else:+ info_msg += "History file: Not found\n"++ except Exception:+ info_msg += "Saved files: Unable to check\n"++ # Add search capability status+ info_msg += "Text search: Enabled (lightweight file-based)\n"++ # Count available session histories+ base_dir = self.working_directory.parent+ session_pattern = str(+ base_dir / "session_*" / f"{self.history_filename}.md"+ )+ session_count = len(glob.glob(session_pattern))+ info_msg += f"Searchable sessions: {session_count}\n"++ return info_msg++ except Exception as e:+ error_msg = f"Failed to get memory info: {e}"+ logger.error(error_msg)+ return error_msg++ def search_full_conversation_history(+ self,+ keywords: List[str],+ top_k: int = 4,+ ) -> str:+ r"""Search the conversation history using keyword matching. This is+ used when information is missing from the summary and the current+ conversation, and can potentially be found in the full conversation+ history before it was summarized.++ Searches through the current session's history.md file to find the+ top messages that contain the most keywords.++ Args:+ keywords (List[str]): List of keywords to search for. The+ keywords must be explicitly related to the information+ the user is looking for, and not general terms that+ might be found about any topic. For example, if the user+ is searching for the price of the flight to "Paris"+ which was discussed previously, the keywords should be+ ["Paris", "price", "flight", "$", "costs"].+ top_k (int): The number of results to return (default 4).++ Returns:+ str: The search results or error message.+ """+ try:+ # Only search current session history+ current_history = (+ self.working_directory / f"{self.history_filename}.md"+ )+ if not current_history.exists():+ return "No history file found in current session."++ logger.info("Searching through current session history")++ # Perform keyword-based search directly+ search_results = self.context_util.search_in_file(+ current_history, keywords, top_k+ )++ if search_results and search_results.strip():+ keywords_str = ", ".join(keywords)+ formatted_results = (+ f"Found relevant conversation excerpts for keywords: "+ f"'{keywords_str}'\n\n"+ f"--- Search Results ---\n"+ f"{search_results}\n"+ f"--- End Results ---\n\n"+ f"Note: Results are ordered by keyword match count."+ )+ return formatted_results+ else:+ keywords_str = ", ".join(keywords)+ return (+ f"No relevant conversations found for keywords: "+ f"'{keywords_str}'. "+ f"Try different keywords."+ )++ except Exception as e:+ error_msg = f"Failed to search conversation history: {e}"+ logger.error(error_msg)+ return error_msg++ def should_compress_context(+ self, message_limit: int = 40, token_limit: Optional[int] = None+ ) -> bool:+ r"""Check if context should be compressed based on limits.++ Args:+ message_limit (int): Maximum number of messages before compression.+ token_limit (Optional[int]): Maximum number of tokens before+ compression.++ Returns:+ bool: True if context should be compressed.+ """+ try:+ # check token limit first (more efficient)+ if token_limit:+ _, token_count = self.agent.memory.get_context()+ if token_count > token_limit:+ return True++ # check message limit+ memory_records = self.context_util.get_agent_memory_records(+ self.agent+ )+ if len(memory_records) > message_limit:+ return True++ return False++ except Exception as e:+ logger.error(+ f"Error checking if context should be compressed: {e}"+ )+ return False++ # ========= UTILITY METHODS =========++ def reset(self) -> None:+ r"""Clear all compression state including stored summaries,+ compressed message tracking, and compression counters."""+ self.existing_summary = None+ self.compressed_message_uuids.clear()+ self.compression_count = 0+ logger.info(+ "Context summarizer toolkit reset - previous summary and "+ "compression tracking cleared"+ )++ def get_current_summary(self) -> Optional[str]:+ r"""Retrieve the in-memory summary without triggering new+ summarization or file operations.++ Returns:+ Optional[str]: The current summary, or None if no summary exists.+ """+ return self.existing_summary++ def set_summary(self, summary: str) -> None:+ r"""Override the current in-memory summary with provided content+ without affecting saved files or compression tracking.++ Args:+ summary (str): The summary to store.+ """+ self.existing_summary = summary+ logger.info("Summary manually set")++ def get_tools(self) -> List[FunctionTool]:+ r"""Get the tools for the ContextSummarizerToolkit.++ Returns:+ List[FunctionTool]: The list of tools.+ """+ return [+ FunctionTool(self.summarize_full_conversation_history),+ FunctionTool(self.search_full_conversation_history),+ FunctionTool(self.get_conversation_memory_info),+ ]diff --git a/camel/toolkits/note_taking_toolkit.py b/camel/toolkits/note_taking_toolkit.pyindex 60e588e32..ed2c28a1a 100644--- a/camel/toolkits/note_taking_toolkit.py+++ b/camel/toolkits/note_taking_toolkit.py@@ -138,33 +138,43 @@ class NoteTakingToolkit(BaseToolkit):self.registry.append(note_name)self._save_registry()- def create_note(self, note_name: str, content: str) -> str:+ def create_note(+ self, note_name: str, content: str, overwrite: bool = False+ ) -> str:r"""Creates a new note with a unique name.This function will create a new file for your note.- You must provide a `note_name` that does not already exist. If you want- to add content to an existing note, use the `append_note` function- instead.+ By default, you must provide a `note_name` that does not already exist.+ If you want to add content to an existing note, use the `append_note`+ function instead. If you want to overwrite an existing note, set+ `overwrite=True`.Args:note_name (str): The name for your new note (without the .md- extension). This name must be unique.+ extension). This name must be unique unless overwrite is True.content (str): The initial content to write in the note.+ overwrite (bool): Whether to overwrite an existing note.+ Defaults to False.Returns:str: A message confirming the creation of the note or an error if- the note name is not valid or already exists.+ the note name is not valid or already exists+ (when overwrite=False)."""try:note_path = self.working_directory / f"{note_name}.md"+ existed_before = note_path.exists()- if note_path.exists():+ if existed_before and not overwrite:return f"Error: Note '{note_name}.md' already exists."note_path.write_text(content, encoding="utf-8")self._register_note(note_name)- return f"Note '{note_name}.md' successfully created."+ if existed_before and overwrite:+ return f"Note '{note_name}.md' successfully overwritten."+ else:+ return f"Note '{note_name}.md' successfully created."except Exception as e:return f"Error creating note: {e}"diff --git a/camel/utils/context_utils.py b/camel/utils/context_utils.pynew file mode 100644index 000000000..132f6086f--- /dev/null+++ b/camel/utils/context_utils.py@@ -0,0 +1,395 @@+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========++import os+from datetime import datetime+from pathlib import Path+from typing import TYPE_CHECKING, Any, Dict, List, Optional++from camel.logger import get_logger++if TYPE_CHECKING:+ from camel.agents import ChatAgent+ from camel.memories.records import MemoryRecord++logger = get_logger(__name__)+++class ContextUtility:+ r"""Utility class for context management and file operations.++ This utility provides generic functionality for managing context files,+ markdown generation, and session management that can be used by+ context-related features.++ Key features:+ - Session-based directory management+ - Generic markdown file operations+ - Text-based search through files+ - File metadata handling+ - Agent memory record retrieval+ """++ def __init__(self, working_directory: Optional[str] = None):+ r"""Initialize the ContextUtility.++ Args:+ working_directory (str, optional): The directory path where files+ will be stored. If not provided, a default directory will be+ used.+ """+ self.working_directory_param = working_directory+ self._setup_storage(working_directory)++ def _setup_storage(self, working_directory: Optional[str]) -> None:+ r"""Initialize session-specific storage paths and create directory+ structure for context file management."""+ self.session_id = self._generate_session_id()++ if working_directory:+ self.working_directory = Path(working_directory).resolve()+ else:+ camel_workdir = os.environ.get("CAMEL_WORKDIR")+ if camel_workdir:+ self.working_directory = Path(camel_workdir) / "context_files"+ else:+ self.working_directory = Path("context_files")++ # Create session-specific directory+ self.working_directory = self.working_directory / self.session_id+ self.working_directory.mkdir(parents=True, exist_ok=True)++ def _generate_session_id(self) -> str:+ r"""Create timestamp-based unique identifier for isolating+ current session files from other sessions."""+ timestamp = datetime.now().strftime('%Y%m%d_%H%M%S_%f')+ return f"session_{timestamp}"++ # ========= GENERIC FILE MANAGEMENT METHODS =========++ def _create_or_update_note(self, note_name: str, content: str) -> str:+ r"""Write content to markdown file, creating new file or+ overwriting existing one with UTF-8 encoding.++ Args:+ note_name (str): Name of the note (without .md extension).+ content (str): Content to write to the note.++ Returns:+ str: Success message.+ """+ try:+ file_path = self.working_directory / f"{note_name}.md"+ with open(file_path, 'w', encoding='utf-8') as f:+ f.write(content)+ return f"Note '{note_name}.md' created successfully"+ except Exception as e:+ logger.error(f"Error creating note {note_name}: {e}")+ return f"Error creating note: {e}"++ def save_markdown_file(+ self,+ filename: str,+ content: str,+ title: Optional[str] = None,+ metadata: Optional[Dict[str, Any]] = None,+ ) -> str:+ r"""Generic method to save any markdown content to a file.++ Args:+ filename (str): Name without .md extension.+ content (str): Main content to save.+ title (str, optional): Title for the markdown file.+ metadata (Dict, optional): Additional metadata to include.++ Returns:+ str: Success message or error message.+ """+ try:+ markdown_content = ""++ # Add title if provided+ if title:+ markdown_content += f"# {title}\n\n"++ # Add metadata section if provided+ if metadata:+ markdown_content += "## Metadata\n\n"+ for key, value in metadata.items():+ markdown_content += f"- {key}: {value}\n"+ markdown_content += "\n"++ # Add main content+ markdown_content += content++ self._create_or_update_note(filename, markdown_content)+ logger.info(+ f"Markdown file saved to "+ f"{self.working_directory / f'{filename}.md'}"+ )+ return f"Markdown file '{filename}.md' saved successfully"++ except Exception as e:+ logger.error(f"Error saving markdown file {filename}: {e}")+ return f"Error saving markdown file: {e}"++ def load_markdown_file(self, filename: str) -> str:+ r"""Generic method to load any markdown file.++ Args:+ filename (str): Name without .md extension.++ Returns:+ str: File content or empty string if not found.+ """+ try:+ file_path = self.working_directory / f"{filename}.md"+ if file_path.exists():+ return file_path.read_text(encoding="utf-8")+ return ""+ except Exception as e:+ logger.error(f"Error loading markdown file {filename}: {e}")+ return ""++ def file_exists(self, filename: str) -> bool:+ r"""Verify presence of markdown file in current session directory.++ Args:+ filename (str): Name without .md extension.++ Returns:+ bool: True if file exists, False otherwise.+ """+ file_path = self.working_directory / f"{filename}.md"+ return file_path.exists()++ def list_markdown_files(self) -> List[str]:+ r"""Discover all markdown files in current session directory+ and return their base names for reference.++ Returns:+ List[str]: List of filenames without .md extension.+ """+ try:+ md_files = list(self.working_directory.glob("*.md"))+ return [f.stem for f in md_files]+ except Exception as e:+ logger.error(f"Error listing markdown files: {e}")+ return []++ # ========= GENERIC AGENT MEMORY METHODS =========++ def get_agent_memory_records(+ self, agent: "ChatAgent"+ ) -> List["MemoryRecord"]:+ r"""Retrieve conversation history from agent's memory system.++ Args:+ agent (ChatAgent): The agent to extract memory records from.++ Returns:+ List[MemoryRecord]: List of memory records from the agent.+ """+ try:+ context_records = agent.memory.retrieve()+ return [cr.memory_record for cr in context_records]+ except Exception as e:+ logger.error(f"Error extracting memory records: {e}")+ return []++ def format_memory_as_conversation(+ self, memory_records: List["MemoryRecord"]+ ) -> str:+ r"""Transform structured memory records into human-readable+ conversation format with role labels and message content.++ Args:+ memory_records (List[MemoryRecord]): Memory records to format.++ Returns:+ str: Formatted conversation text.+ """+ conversation_lines = []++ for record in memory_records:+ role = (+ record.role_at_backend.value+ if hasattr(record.role_at_backend, 'value')+ else str(record.role_at_backend)+ )+ content = record.message.content+ conversation_lines.append(f"{role}: {content}")++ return "\n".join(conversation_lines)++ # ========= SESSION MANAGEMENT METHODS =========++ def create_session_directory(+ self, base_dir: Optional[str] = None, session_id: Optional[str] = None+ ) -> Path:+ r"""Create a session-specific directory.++ Args:+ base_dir (str, optional): Base directory. If None, uses current+ working directory.+ session_id (str, optional): Custom session ID. If None, generates+ new one.++ Returns:+ Path: The created session directory path.+ """+ if session_id is None:+ session_id = self._generate_session_id()++ if base_dir:+ base_path = Path(base_dir).resolve()+ else:+ base_path = self.working_directory.parent++ session_dir = base_path / session_id+ session_dir.mkdir(parents=True, exist_ok=True)+ return session_dir++ def get_session_metadata(self) -> Dict[str, Any]:+ r"""Collect comprehensive session information including identifiers,+ timestamps, and directory paths for tracking and reference.++ Returns:+ Dict[str, Any]: Session metadata including ID, timestamp,+ directory.+ """+ return {+ 'session_id': self.session_id,+ 'working_directory': str(self.working_directory),+ 'created_at': datetime.now().isoformat(),+ 'base_directory': str(self.working_directory.parent),+ }++ def list_sessions(self, base_dir: Optional[str] = None) -> List[str]:+ r"""Discover all available session directories for browsing+ historical conversations and context files.++ Args:+ base_dir (str, optional): Base directory to search. If None, uses+ parent of working directory.++ Returns:+ List[str]: List of session directory names.+ """+ try:+ if base_dir:+ search_dir = Path(base_dir)+ else:+ search_dir = self.working_directory.parent++ session_dirs = [+ d.name+ for d in search_dir.iterdir()+ if d.is_dir() and d.name.startswith('session_')+ ]+ return sorted(session_dirs)+ except Exception as e:+ logger.error(f"Error listing sessions: {e}")+ return []++ # ========= GENERIC SEARCH METHODS =========++ def search_in_file(+ self, file_path: Path, keywords: List[str], top_k: int = 4+ ) -> str:+ r"""Perform keyword-based search through file sections,+ ranking results by keyword frequency and returning top matches.++ Args:+ file_path (Path): Path to the file to search.+ keywords (List[str]): Keywords to search for.+ top_k (int): Maximum number of results to return.++ Returns:+ str: Formatted search results.+ """+ results: List[Dict[str, Any]] = []+ keyword_terms = [keyword.lower() for keyword in keywords]++ try:+ if not file_path.exists():+ return ""++ with open(file_path, 'r', encoding='utf-8') as f:+ content = f.read()++ # Split content into sections (assuming ### headers)+ sections = content.split('### ')[1:] # Skip the header part++ for i, section in enumerate(sections):+ if not section.strip():+ continue++ section_lower = section.lower()++ # count how many keywords appear in this section+ keyword_matches = sum(+ 1 for keyword in keyword_terms if keyword in section_lower+ )++ if keyword_matches > 0:+ results.append(+ {+ 'content': f"### {section.strip()}",+ 'keyword_count': keyword_matches,+ 'section_num': i + 1,+ }+ )++ except Exception as e:+ logger.warning(f"Error reading file {file_path}: {e}")+ return ""++ # sort by keyword count and limit results+ results.sort(key=lambda x: x['keyword_count'], reverse=True)+ results = results[:top_k]++ if not results:+ return ""++ # format results+ formatted_sections = []+ for result in results:+ formatted_sections.append(+ f"Section {result['section_num']} "+ f"(keyword matches: {result['keyword_count']}):\n"+ f"{result['content']}\n"+ )++ return "\n---\n".join(formatted_sections)++ # ========= UTILITY METHODS =========++ def get_working_directory(self) -> Path:+ r"""Retrieve the session-specific directory path where+ all context files are stored.++ Returns:+ Path: The working directory path.+ """+ return self.working_directory++ def get_session_id(self) -> str:+ r"""Retrieve the unique identifier for the current session+ used for file organization and tracking.++ Returns:+ str: The session ID.+ """+ return self.session_iddiff --git a/examples/toolkits/context_summarizer_toolkit.py b/examples/toolkits/context_summarizer_toolkit.pynew file mode 100644index 000000000..fbe72f6be--- /dev/null+++ b/examples/toolkits/context_summarizer_toolkit.py@@ -0,0 +1,431 @@+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========++from camel.agents import ChatAgent+from camel.models.model_factory import ModelFactory+from camel.toolkits.context_summarizer_toolkit import ContextSummarizerToolkit+from camel.types import ModelPlatformType, ModelType++"""+This example demonstrates the ContextSummarizerToolkit, which provides+intelligent context summarization and memory management capabilities for+ChatAgent. The toolkit enables agents to:+1. Manually save conversation memory when context becomes cluttered+2. Load previous context summaries+3. Search through conversation history using text search+4. Get information about current memory state+5. Check if context should be compressed based on message/token limits++The toolkit is particularly useful when you want the agent to have control over+when to save/refresh memory, rather than relying on automatic thresholds.+"""++# Set up directory for saving context files+memory_dir = "./agent_context_toolkit"++model = ModelFactory.create(+ model_platform=ModelPlatformType.DEFAULT,+ model_type=ModelType.DEFAULT,+)++# Create agent without auto-compression - we'll use the toolkit for manual+# control+agent = ChatAgent(+ system_message="""You are a helpful AI assistant providing travel """+ """advice.""",+ model=model,+ agent_id="context_toolkit_agent_001",+)++# Initialize the context summarizer toolkit+context_toolkit = ContextSummarizerToolkit(+ agent=agent,+ working_directory=memory_dir,+)++# Add toolkit to agent+agent.add_tools(context_toolkit.get_tools())++print("=== ContextSummarizerToolkit Example ===\n")++# 1. Start conversation about travel planning+user_input_1 = (+ "Hello my name is John. I'm planning a trip to Japan in "+ "spring. What are the best cities to visit?"+)+response_1 = agent.step(user_input_1)+print(f"User: {user_input_1}")+print(f"Assistant: {response_1.msgs[0].content}\n")++'''+===============================================================================+Assistant: In spring, Japan is especially beautiful with cherry blossoms in+full bloom. Here are some of the best cities to visit:++1. **Tokyo**: The bustling capital offers a mix of modern life and+traditional culture. Don't miss Ueno Park and Shinjuku Gyoen for+cherry blossom viewing.++2. **Kyoto**: Known for its classical Buddhist temples, beautiful gardens,+and traditional wooden houses. The Philosopher's Path is lined with+hundreds of cherry trees.++3. **Osaka**: A lively city known for modern architecture, vibrant+nightlife, and delicious street food. Osaka Castle is a great spot+for hanami.++4. **Nara**: Home to free-roaming deer and the impressive Todaiji Temple.+Nara Park is another great place for cherry blossoms.++5. **Hiroshima**: Visit the Peace Memorial Park and Museum. Nearby+Miyajima Island is famous for its floating torii gate and beautiful+cherry blossoms.++6. **Sapporo**: Sapporo in Hokkaido is known for its late-blooming+cherry blossoms, and offers a different perspective from mainland Japan.++7. **Kanazawa**: Known for its well-preserved Edo-era districts, art+museums, and beautiful gardens like Kenrokuen.++8. **Fukuoka**: Offers a mix of modern city life and historical sites.+Fukuoka Castle ruins are surrounded by cherry blossoms in Maizuru Park.++These cities provide a mix of modern attractions and historical sites, all+enhanced by the seasonal beauty of cherry blossoms. Let me know if you need+more details on any specific city or travel tips!+===============================================================================+'''++# 2. Continue with more details+user_input_2 = (+ "How many days should I spend in Tokyo? I'm interested in "+ "culture and food."+)+response_2 = agent.step(user_input_2)+print(f"User: {user_input_2}")+print(f"Assistant: {response_2.msgs[0].content}\n")++'''+===============================================================================+Assistant: To fully experience Tokyo's rich culture and diverse food scene,+I recommend spending at least 4 to 5 days in the city. Here's a suggested+breakdown to make the most of your stay:++**Day 1: Explore Traditional Tokyo**+- Visit Asakusa for Senso-ji Temple and traditional shopping streets.+- Explore the historic Tokyo Imperial Palace and its surrounding gardens.+- Enjoy dinner at a traditional izakaya (Japanese pub) in the area.++**Day 2: Discover Modern Tokyo**+- Spend time in Shibuya and Shinjuku to see the bustling city life.+- Explore Harajuku's trendy fashion and unique cafes.+- Visit the observation deck at Tokyo Metropolitan Government Building+ for a panoramic city view.+- Enjoy modern Japanese cuisine or sushi at a renowned Tokyo restaurant.++**Day 3: Dive into Tokyo's Art and History**+- Visit Ueno Park and museums like the Tokyo National Museum and Ueno Zoo.+- Explore Akihabara for electronics, anime, and manga culture.+- Taste local dishes like monjayaki or okonomiyaki.++**Day 4: Experience Tokyo's Culinary Scene**+- Join a food tour to explore Tsukiji Outer Market for fresh seafood.+- Wander through different neighborhoods to try ramen, tempura, and+ more street food.+- Visit Ginza for upscale shopping and dining.++**Day 5 (Optional): Day Trip or Special Interest**+- Consider a day trip to nearby Nikko or Kamakura for historical exploration.+- Enjoy a themed cafe experience or attend a cultural workshop+ (e.g., tea ceremony).++This itinerary gives you a balanced mix of cultural, historical, and+culinary experiences, highlighting the dynamic and diverse facets of Tokyo.+===============================================================================+'''++# 3. Add more complexity+user_input_3 = "What's the best way to travel between cities in Japan?"+response_3 = agent.step(user_input_3)+print(f"User: {user_input_3}")+print(f"Assistant: {response_3.msgs[0].content}\n")++'''+===============================================================================+Assistant: The best way to travel between cities in Japan is by using the+country's efficient and reliable train system. Here are some of the most+popular options:++1. **Shinkansen (Bullet Train)**:+ - The Shinkansen is the fastest and most convenient way to travel+ between major cities such as Tokyo, Kyoto, Osaka, Hiroshima, and more.+ - It's known for its punctuality and comfort. You can reserve seats in+ advance for longer journeys, which is often recommended during busy+ travel seasons.+ - Consider purchasing a Japan Rail Pass (JR Pass) if you plan to travel+ extensively by train. It offers unlimited rides on most Shinkansen lines+ and JR trains for a set period (7, 14, or 21 days), which can be very+ cost-effective.++2. **Limited Express Trains**:+ - For routes not covered by the Shinkansen, Limited Express trains run+ frequently and are also comfortable.+ - These are ideal for shorter distances or routes within certain regions.++3. **Local Trains**:+ - Local trains are available for shorter distances and are often more+ economical, but they might take longer.++4. **Domestic Flights**:+ - For distant cities, like traveling from Tokyo to Sapporo or Okinawa,+ domestic flights might be more convenient.+ - Low-cost carriers and domestic airlines offer frequent flights between+ major airports.++5. **Bus Services**:+ - Highway buses are a cost-effective alternative to trains for+ long-distance travel. They might take longer but are suitable for+ overnight travel.++6. **Car Rental**:+ - Renting a car is an option if you want to explore more rural or remote+ areas. However, navigating cities like Tokyo can be challenging due to+ traffic and parking limitations.++Each mode of transportation has its benefits depending on your itinerary,+budget, and preferences. Using a mix of these options can help optimize your+travel experience in Japan.+===============================================================================+'''++# 4. Continue building context+user_input_4 = "Should I book accommodations in advance?"+response_4 = agent.step(user_input_4)+print(f"User: {user_input_4}")+print(f"Assistant: {response_4.msgs[0].content}\n")++'''+===============================================================================+Assistant: Yes, it is generally advisable to book accommodations in advance,+especially when traveling to popular destinations like Tokyo, Kyoto, and+Osaka during peak tourist seasons. Here are some reasons why booking ahead+is a good idea:++1. **Availability**: Popular hotels and unique accommodations (like ryokans,+traditional Japanese inns) can fill up quickly, especially during cherry+blossom season in spring or autumn for the fall foliage.++2. **Cost**: Booking early often allows you to take advantage of early bird+rates and promotions. Prices can increase significantly as your travel dates+approach, particularly in popular areas.++3. **Choice**: You'll have a wider selection of accommodations to choose+from, ensuring that you can find a place that fits your preferences for+comfort, location, and amenities.++4. **Peace of Mind**: Having your accommodations sorted in advance adds+convenience and reduces stress, allowing you to focus on planning other+aspects of your trip.++5. **Flexibility**: Many hotels and booking platforms offer flexible+cancellation policies, so you can often make changes if needed.++To ensure a smooth and enjoyable experience, consider researching and+booking your accommodations a few months in advance, especially if you have+specific places or experiences you'd like to include in your itinerary.+===============================================================================+'''++# 5. Add more topics - this will make context more complex+user_input_5 = "What are some essential Japanese phrases for travelers?"+response_5 = agent.step(user_input_5)+print(f"User: {user_input_5}")+print(f"Assistant: {response_5.msgs[0].content}\n")++'''+===============================================================================+Assistant: Learning a few essential Japanese phrases can greatly enhance your+travel experience in Japan, as it shows respect for the local culture and+can help in communication. Here are some helpful phrases:++1. **Basic Greetings:**+ - Hello: ใใใซใกใฏ (Konnichiwa)+ - Good morning: ใใฏใใใใใใพใ (Ohayou gozaimasu)+ - Good evening: ใใใฐใใฏ (Konbanwa)+ - Goodbye: ใใใใชใ (Sayonara)++2. **Polite Expressions:**+ - Thank you: ใใใใจใ (Arigatou) /+ ใใใใจใใใใใพใ (Arigatou gozaimasu)+ - Please: ใ้กใใใพใ (Onegaishimasu)+ - Excuse me / I'm sorry: ใใฟใพใใ (Sumimasen)++3. **Common Questions:**+ - Do you speak English?: ่ฑ่ชใ่ฉฑใใพใใ?(Eigo o hanasemasu ka?)+ - How much is this?: ใใใฏใใใใงใใ?(Kore wa ikura desu ka?)+ - Where is the bathroom?: ใใคใฌใฏใฉใใงใใ?(Toire wa doko desu ka?)+ - Can you help me?: ๆไผใฃใฆใใใพใใ?(Tetsudatte kuremasu ka?)++4. **Dining:**+ - I would like this: ใใใใ้กใใใพใ (Kore o onegaishimasu)+ - Delicious: ใใใใ (Oishii)+ - Check, please: ใไผ่จใใ้กใใใพใ (O-kaikei o onegaishimasu)++5. **Travel:**+ - Where is the train station?: ้ง ใฏใฉใใงใใ?(Eki wa doko desu ka?)+ - I need a taxi: ใฟใฏใทใผใใ้กใใใพใ (Takushii o onegaishimasu)+ - A ticket to [destination], please: [็ฎ็ๅฐ]่กใใฎใใฑใใใ+ ใ้กใใใพใ ([Mokutekichi] yuki no chiketto o onegaishimasu)++6. **Emergency:**+ - Help!: ๅฉใใฆ!(Tasukete!)+ - Call a doctor: ๅป่ ใๅผใใงใใ ใใ (Isha o yonde kudasai)++These phrases cover a variety of situations you might encounter during your+trip. It's also helpful to have a translation app or phrasebook on hand for+more complex conversations.+===============================================================================+'''++print("=== Asking agent to check memory status ===")+# 6. Ask agent to check memory status+user_input_6 = "Can you check our current memory status using your tools?"+response_6 = agent.step(user_input_6)+print(f"User: {user_input_6}")+print(f"Assistant: {response_6.msgs[0].content}\n")++'''+===============================================================================+Assistant: Our current memory status has 12 messages in memory, and there are+no summary or history files saved yet. We can store summaries or history of+our conversations, and you can also perform text searches within these+sessions if needed. If you have any specific requirements or need a summary,+feel free to let me know!+===============================================================================+'''++print("=== Suggesting agent save memory ===")+# 7. Suggest agent save memory as conversation is getting complex+user_input_7 = (+ "We've covered a lot of ground on Japan travel. Maybe you "+ "should save our conversation memory to keep things "+ "organized?"+)+response_7 = agent.step(user_input_7)+print(f"User: {user_input_7}")+print(f"Assistant: {response_7.msgs[0].content}\n")++'''+===============================================================================+Assistant: I've cleared some of the previous conversation for a fresh start.+How can I assist you with your travel plans today?+===============================================================================+'''++print("=== Starting new topic after memory save ===")+# 8. Start a new topic to test context refresh+user_input_8 = (+ "Now I want to ask about something completely different - can "+ "you help me plan a workout routine?"+)+response_8 = agent.step(user_input_8)+print(f"User: {user_input_8}")+print(f"Assistant: {response_8.msgs[0].content}\n")++'''+===============================================================================+Assistant: Sure, I can help you plan a workout routine! Could you tell me a+bit about your fitness goals and any preferences or limitations you have?+===============================================================================+'''++print("=== Testing memory recall ===")+# 9. Test if agent can recall previous context when needed+user_input_9 = (+ "Wait, let me go back to my Japan trip. What was my name "+ "again, and what did we discuss about Tokyo?"+)+response_9 = agent.step(user_input_9)+print(f"User: {user_input_9}")+print(f"Assistant: {response_9.msgs[0].content}\n")++'''+===============================================================================+Assistant: Your name is John, and we discussed your trip to Japan.+Specifically about Tokyo, we talked about its modern attractions and+traditional sites, like visiting Shinjuku Gyoen Park for cherry blossoms,+and exploring areas such as Shibuya and Akihabara. Is there anything more+you'd like to know or plan regarding your visit to Tokyo?+===============================================================================+'''++print("=== Testing text search ===")+# 10. Test text search functionality+user_input_10 = (+ "Can you search our conversation history for information "+ "about transportation in Japan?"+)+response_10 = agent.step(user_input_10)+print(f"User: {user_input_10}")+print(f"Assistant: {response_10.msgs[0].content}\n")++'''+===============================================================================+Assistant: We discussed various transportation options in Japan, particularly+focusing on the train system. Here are some key points:++1. **Shinkansen (Bullet Train)**: The fastest and most convenient way to+travel between major cities like Tokyo, Kyoto, and Osaka. It's punctual and+comfortable. If you plan to use trains extensively, a Japan Rail Pass is+recommended.++2. **Limited Express Trains**: These are suitable for routes not covered by+the Shinkansen and are ideal for shorter distances within certain regions.++3. **Local Trains**: More economical but slower, ideal for shorter distances.++4. **Domestic Flights**: Useful for traveling to distant cities like+Sapporo or Okinawa.++5. **Bus Services**: A cost-effective alternative to trains, suitable for+long-distance travel including overnight trips.++6. **Car Rental**: An option if exploring rural areas, but navigating cities+like Tokyo might be challenging.++Each transportation mode has its benefits depending on your itinerary and+preferences. Is there anything more specific you'd like to know?+===============================================================================+'''++print("=== Final memory check ===")+# 11. Final memory status check+user_input_11 = (+ "Can you give me a final status of our memory management for this session?"+)+response_11 = agent.step(user_input_11)+print(f"User: {user_input_11}")+print(f"Assistant: {response_11.msgs[0].content}\n")++'''+===============================================================================+Assistant: Currently, we have 16 messages in memory, and a summary of our+conversation is available with 1,544 characters. The full conversation history+file contains 11,212 characters. Our memory management utilizes a lightweight+file-based text search, and there are 8 searchable sessions. Is there anything+else you need help with regarding our session or your trip planning?+===============================================================================+'''++print("\n=== Example Complete ===")diff --git a/test/toolkits/test_context_summarizer_toolkit.py b/test/toolkits/test_context_summarizer_toolkit.pynew file mode 100644index 000000000..f36642ab5--- /dev/null+++ b/test/toolkits/test_context_summarizer_toolkit.py@@ -0,0 +1,384 @@+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========++import tempfile+from pathlib import Path+from unittest.mock import MagicMock, patch++import pytest++from camel.agents import ChatAgent+from camel.memories import MemoryRecord+from camel.memories.records import ContextRecord+from camel.messages.base import BaseMessage+from camel.models import BaseModelBackend+from camel.toolkits.context_summarizer_toolkit import ContextSummarizerToolkit+from camel.types import RoleType+from camel.types.enums import OpenAIBackendRole++[email protected](scope="function")+def temp_directory():+ r"""Create a temporary directory for test files."""+ with tempfile.TemporaryDirectory() as temp_dir:+ yield temp_dir++[email protected](scope="function")+def mock_agent():+ r"""Create a mock ChatAgent for testing."""+ agent = MagicMock(spec=ChatAgent)+ agent.agent_id = "test_agent_001"++ # Create a mock model backend that behaves like a real one+ mock_model = MagicMock(spec=BaseModelBackend)+ mock_model.token_counter = MagicMock()+ mock_model.token_limit = 1000+ agent.model_backend = mock_model++ agent.memory = MagicMock()+ agent.clear_memory = MagicMock()+ agent.update_memory = MagicMock()+ return agent++[email protected](scope="function")+def sample_messages():+ r"""Create sample messages for testing."""+ messages = []++ # Create a conversation about travel planning+ user_msg1 = BaseMessage(+ role_name="User",+ role_type=RoleType.USER,+ meta_dict={},+ content="Hello my name is John. I'm planning a trip to Japan in "+ "spring. What are the best cities to visit?",+ )++ assistant_msg1 = BaseMessage(+ role_name="Assistant",+ role_type=RoleType.ASSISTANT,+ meta_dict={},+ content="Japan in the spring is a beautiful time to visit. Here are "+ "some of the best cities: Tokyo, Kyoto, Osaka, and Hiroshima.",+ )++ user_msg2 = BaseMessage(+ role_name="User",+ role_type=RoleType.USER,+ meta_dict={},+ content="What's the best way to travel between cities in Japan?",+ )++ assistant_msg2 = BaseMessage(+ role_name="Assistant",+ role_type=RoleType.ASSISTANT,+ meta_dict={},+ content="The best way to travel between cities in Japan is by "+ "Shinkansen (bullet train). Consider getting a JR Pass for "+ "multiple cities.",+ )++ messages.extend([user_msg1, assistant_msg1, user_msg2, assistant_msg2])+ return messages++[email protected](scope="function")+def sample_memory_records(sample_messages):+ r"""Create sample memory records from messages."""+ records = []+ for msg in sample_messages:+ backend_role = (+ OpenAIBackendRole.USER+ if msg.role_type == RoleType.USER+ else OpenAIBackendRole.ASSISTANT+ )+ record = MemoryRecord(+ message=msg,+ role_at_backend=backend_role,+ agent_id="test_agent_001",+ )+ records.append(record)+ return records++[email protected](scope="function")+def sample_context_records(sample_memory_records):+ r"""Create sample context records for testing."""+ context_records = []+ for record in sample_memory_records:+ context_record = ContextRecord(memory_record=record, score=1.0)+ context_records.append(context_record)+ return context_records++[email protected](scope="function")+def context_summarizer_toolkit_fixture(mock_agent, temp_directory):+ r"""Create a ContextSummarizerToolkit instance for testing."""+ with patch('camel.agents.ChatAgent') as mock_chat_agent:+ # Create a mock summary agent+ mock_summary_agent = MagicMock()+ mock_summary_agent.agent_id = f"{mock_agent.agent_id}_summarizer"+ mock_summary_agent.reset = MagicMock()+ mock_summary_agent.step = MagicMock()+ mock_chat_agent.return_value = mock_summary_agent++ toolkit = ContextSummarizerToolkit(+ agent=mock_agent,+ working_directory=temp_directory,+ )+ return toolkit+++def test_toolkit_initialization(+ context_summarizer_toolkit_fixture, temp_directory+):+ r"""Test that the toolkit initializes correctly."""+ toolkit = context_summarizer_toolkit_fixture+ assert toolkit.agent is not None+ assert (+ toolkit.working_directory.parent.resolve()+ == Path(temp_directory).resolve()+ )+ assert toolkit.session_id is not None+ assert toolkit.summary_filename == "agent_memory_summary"+ assert toolkit.history_filename == "agent_memory_history"+ assert toolkit.working_directory.exists()+++def test_summary_saves_to_markdown_files(+ context_summarizer_toolkit_fixture, sample_context_records+):+ r"""Test that agent correctly saves summary in two .md files."""+ toolkit = context_summarizer_toolkit_fixture++ # Mock the agent's memory retrieve method+ toolkit.agent.memory.retrieve.return_value = sample_context_records++ # Mock the summary agent response+ mock_response = MagicMock()+ mock_response.msgs = [MagicMock()]+ mock_response.msgs[0].content = (+ "Summary: John is planning a trip to Japan in spring. We "+ "discussed cities like Tokyo, Kyoto, and transportation via "+ "Shinkansen."+ )++ with patch.object(+ toolkit.summary_agent, 'step', return_value=mock_response+ ):+ # Call the summarization function+ result = toolkit.summarize_full_conversation_history()++ # Check that the function completed successfully+ assert "Full context summarized" in result++ # Check that both files exist+ summary_file = toolkit.working_directory / "agent_memory_summary.md"+ history_file = toolkit.working_directory / "agent_memory_history.md"++ assert summary_file.exists(), "Summary file should be created"+ assert history_file.exists(), "History file should be created"++ # Read and verify summary file content+ summary_content = summary_file.read_text(encoding="utf-8")+ assert "# Conversation Summary:" in summary_content+ assert "Session ID:" in summary_content+ assert "John is planning a trip to Japan" in summary_content++ # Read and verify history file content+ history_content = history_file.read_text(encoding="utf-8")+ assert "# Conversation History:" in history_content+ assert "Total Messages: 4" in history_content+ assert "Japan in spring" in history_content+ assert "Shinkansen" in history_content+ assert "Message 1 - User" in history_content+ assert "Message 2 - Assistant" in history_content+++def test_conversation_history_removal_and_summary_push(+ context_summarizer_toolkit_fixture, sample_context_records+):+ r"""Test that agent removes conversation history and pushes summary."""+ toolkit = context_summarizer_toolkit_fixture++ # Setup mock agent memory+ toolkit.agent.memory.retrieve.return_value = sample_context_records++ # Mock the summary agent response+ mock_response = MagicMock()+ mock_response.msgs = [MagicMock()]+ summary_text = (+ "Summary: John is planning Japan trip. Discussed Tokyo, Kyoto, "+ "Shinkansen transport."+ )+ mock_response.msgs[0].content = summary_text++ with patch.object(+ toolkit.summary_agent, 'step', return_value=mock_response+ ):+ # Call summarization+ result = toolkit.summarize_full_conversation_history()++ # Verify that clear_memory was called (history removal)+ toolkit.agent.clear_memory.assert_called_once()++ # Verify that update_memory was called with summary (summary push)+ toolkit.agent.update_memory.assert_called_once()++ # Check the arguments passed to update_memory+ call_args = toolkit.agent.update_memory.call_args+ summary_message = call_args[0][0] # First argument (message)+ backend_role = call_args[0][1] # Second argument (role)++ # Verify the summary message content+ assert "[Context Summary]" in summary_message.content+ assert summary_text in summary_message.content+ assert backend_role == OpenAIBackendRole.SYSTEM++ # Verify successful completion+ assert "Full context summarized" in result+++def test_keyword_search_functionality(+ context_summarizer_toolkit_fixture, sample_context_records+):+ r"""Test that agent correctly searches conversation history."""+ toolkit = context_summarizer_toolkit_fixture++ # Setup the toolkit with sample data first+ toolkit.agent.memory.retrieve.return_value = sample_context_records++ # Create history file with sample data+ mock_response = MagicMock()+ mock_response.msgs = [MagicMock()]+ mock_response.msgs[0].content = "Test summary for search."++ with patch.object(+ toolkit.summary_agent, 'step', return_value=mock_response+ ):+ # First save the conversation to create history file+ toolkit.summarize_full_conversation_history()++ # Test keyword search+ search_keywords = ["Japan", "travel", "Tokyo"]+ search_result = toolkit.search_full_conversation_history(+ keywords=search_keywords, top_k=2+ )++ # Verify search results format+ assert "Found relevant conversation excerpts" in search_result+ assert "Japan, travel, Tokyo" in search_result+ assert "Search Results" in search_result+ assert "keyword matches:" in search_result++ # Test with keywords that should match our sample data+ japan_results = toolkit.search_full_conversation_history(+ keywords=["Japan", "spring"], top_k=3+ )+ assert "Japan, spring" in japan_results+ assert "Message" in japan_results++ # Test with keywords that won't match+ no_match_results = toolkit.search_full_conversation_history(+ keywords=["Python", "coding"], top_k=2+ )+ assert "No relevant conversations found" in no_match_results+++def test_memory_info_functionality(+ context_summarizer_toolkit_fixture, sample_context_records+):+ r"""Test memory info reporting functionality."""+ toolkit = context_summarizer_toolkit_fixture++ # Setup mock memory+ toolkit.agent.memory.retrieve.return_value = sample_context_records++ # Get memory info+ info_result = toolkit.get_conversation_memory_info()++ # Verify info format+ assert "Current messages in memory: 4" in info_result+ assert "Save directory:" in info_result+ assert "Summary file:" in info_result+ assert "History file:" in info_result+ assert "Text search: Enabled" in info_result+++def test_should_compress_context(+ context_summarizer_toolkit_fixture, sample_context_records+):+ r"""Test context compression decision logic."""+ toolkit = context_summarizer_toolkit_fixture++ # Setup mock memory+ toolkit.agent.memory.retrieve.return_value = sample_context_records++ # Test with low message limit - should compress+ should_compress_low = toolkit.should_compress_context(message_limit=2)+ assert should_compress_low is True++ # Test with high message limit - should not compress+ should_compress_high = toolkit.should_compress_context(message_limit=10)+ assert should_compress_high is False++ # Test with token limit+ toolkit.agent.memory.get_context.return_value = ("context", 500)+ should_compress_tokens = toolkit.should_compress_context(+ message_limit=10, token_limit=400+ )+ assert should_compress_tokens is True+++def test_over_compression_prevention(+ context_summarizer_toolkit_fixture, sample_memory_records+):+ r"""Test that over-compression is prevented."""+ toolkit = context_summarizer_toolkit_fixture++ # Mock summary agent+ mock_response = MagicMock()+ mock_response.msgs = [MagicMock()]+ mock_response.msgs[0].content = "First summary"++ with patch.object(+ toolkit.summary_agent, 'step', return_value=mock_response+ ):+ # First summarization+ first_summary = toolkit._summarize_messages(sample_memory_records)+ assert "First summary" in first_summary++ # Second attempt should return existing summary+ second_summary = toolkit._summarize_messages(sample_memory_records)+ assert second_summary == "First summary"+++def test_empty_memory_handling(context_summarizer_toolkit_fixture):+ r"""Test handling of empty conversation memory."""+ toolkit = context_summarizer_toolkit_fixture++ # Setup empty memory+ toolkit.agent.memory.retrieve.return_value = []++ # Test summarization with empty memory+ result = toolkit.summarize_full_conversation_history()+ assert "No conversation history found" in result+++if __name__ == "__main__":+ import sys++ pytest.main([sys.argv[0]])