🐫 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: add summarize function in agent using context util (#3149)
Xiaotian Jinaf318018e015
diff --git a/camel/agents/chat_agent.py b/camel/agents/chat_agent.pyindex a9ea5d2aa..011cd2df1 100644--- a/camel/agents/chat_agent.py+++ b/camel/agents/chat_agent.py@@ -23,6 +23,7 @@ import textwrapimport threadingimport timeimport uuid+from datetime import datetimefrom pathlib import Pathfrom typing import (TYPE_CHECKING,@@ -93,6 +94,7 @@ from camel.utils import (model_from_json_schema,)from camel.utils.commons import dependencies_required+from camel.utils.context_utils import ContextUtilityif TYPE_CHECKING:from camel.terminators import ResponseTerminator@@ -535,6 +537,8 @@ class ChatAgent(BaseAgent):self.retry_attempts = max(1, retry_attempts)self.retry_delay = max(0.0, retry_delay)self.step_timeout = step_timeout+ self._context_utility: Optional[ContextUtility] = None+ self._context_summary_agent: Optional["ChatAgent"] = Noneself.stream_accumulate = stream_accumulatedef reset(self):@@ -1042,6 +1046,149 @@ class ChatAgent(BaseAgent):json_store.save(to_save)logger.info(f"Memory saved to {path}")+ def summarize(+ self,+ filename: Optional[str] = None,+ summary_prompt: Optional[str] = None,+ ) -> Dict[str, Any]:+ r"""Summarize the agent's current conversation context and persist it+ to a markdown file.++ Args:+ filename (Optional[str]): The base filename (without extension) to+ use for the markdown file. Defaults to a timestamped name when+ not provided.+ summary_prompt (Optional[str]): Custom prompt for the summarizer.+ When omitted, a default prompt highlighting key decisions,+ action items, and open questions is used.++ Returns:+ Dict[str, Any]: A dictionary containing the summary text, file+ path, and status message.+ """++ result: Dict[str, Any] = {+ "summary": "",+ "file_path": None,+ "status": "",+ }++ try:+ if self._context_utility is None:+ self._context_utility = ContextUtility()++ # Get conversation directly from agent's memory+ messages, _ = self.memory.get_context()++ if not messages:+ status_message = (+ "No conversation context available to summarize."+ )+ result["status"] = status_message+ return result++ # Convert messages to conversation text+ conversation_lines = []+ for message in messages:+ role = message.get('role', 'unknown')+ content = message.get('content', '')+ if content:+ conversation_lines.append(f"{role}: {content}")++ conversation_text = "\n".join(conversation_lines).strip()++ if not conversation_text:+ status_message = (+ "Conversation context is empty; skipping summary."+ )+ result["status"] = status_message+ return result++ if self._context_summary_agent is None:+ self._context_summary_agent = ChatAgent(+ system_message=(+ "You are a helpful assistant that summarizes "+ "conversations into concise markdown bullet lists."+ ),+ model=self.model_backend,+ agent_id=f"{self.agent_id}_context_summarizer",+ )+ else:+ self._context_summary_agent.reset()++ prompt_text = summary_prompt or (+ "Summarize the following conversation in concise markdown "+ "bullet points highlighting key decisions, action items, and "+ "open questions.\n\n"+ f"{conversation_text}"+ )++ try:+ response = self._context_summary_agent.step(prompt_text)+ except Exception as step_exc:+ error_message = (+ f"Failed to generate summary using model: {step_exc}"+ )+ logger.error(error_message)+ result["status"] = error_message+ return result++ if not response.msgs:+ status_message = (+ "Failed to generate summary from model response."+ )+ result["status"] = status_message+ return result++ summary_content = response.msgs[-1].content.strip()+ if not summary_content:+ status_message = "Generated summary is empty."+ result["status"] = status_message+ return result++ base_filename = (+ filename+ if filename+ else f"context_summary_{datetime.now().strftime('%Y%m%d_%H%M%S')}" # noqa: E501+ )+ base_filename = Path(base_filename).with_suffix("").name++ metadata = self._context_utility.get_session_metadata()+ metadata.update(+ {+ "agent_id": self.agent_id,+ "message_count": len(messages),+ }+ )++ save_status = self._context_utility.save_markdown_file(+ base_filename,+ summary_content,+ title="Conversation Summary",+ metadata=metadata,+ )++ file_path = (+ self._context_utility.get_working_directory()+ / f"{base_filename}.md"+ )++ result.update(+ {+ "summary": summary_content,+ "file_path": str(file_path),+ "status": save_status,+ }+ )+ logger.info("Conversation summary saved to %s", file_path)+ return result++ except Exception as exc:+ error_message = f"Failed to summarize conversation context: {exc}"+ logger.error(error_message)+ result["status"] = error_message+ return result+def clear_memory(self) -> None:r"""Clear the agent's memory and reset to initial state.diff --git a/examples/agents/agent_summarize.py b/examples/agents/agent_summarize.pynew file mode 100644index 000000000..92d0352eb--- /dev/null+++ b/examples/agents/agent_summarize.py@@ -0,0 +1,117 @@+# ========= 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. =========+"""Example showing how to summarize an agent conversation to markdown."""++from __future__ import annotations++from camel.agents import ChatAgent+from camel.models import ModelFactory+from camel.toolkits import FunctionTool+from camel.types import ModelPlatformType, ModelType+++def calculate_add(a: int, b: int) -> int:+ """Add two integers and return the result."""++ return a + b+++def calculate_multiply(a: int, b: int) -> int:+ """Multiply two integers and return the product."""++ return a * b+++def main() -> None:+ """Run a short interaction and persist the summary to markdown."""++ system_message = (+ "You are a helpful assistant that can call math tools when needed."+ )++ model = ModelFactory.create(+ model_platform=ModelPlatformType.DEFAULT,+ model_type=ModelType.DEFAULT,+ )++ add_tool = FunctionTool(calculate_add)+ multiply_tool = FunctionTool(calculate_multiply)++ agent = ChatAgent(+ system_message=system_message,+ model=model,+ tools=[add_tool, multiply_tool],+ )++ # Interact with the agent so it has context to summarize.+ agent.step("We are preparing a math practice worksheet for students.")++ agent.step(+ "Compute 27 + 15 using the add tool to double-check the answer."+ )++ agent.step("Now multiply the result by 3.")++ # Summarize the conversation to a markdown file in the context directory.+ summary_result = agent.summarize(filename="math_planning_summary")++ print(summary_result.get("status", ""))+ if summary_result.get("file_path"):+ print(f"Summary saved to: {summary_result['file_path']}")++ if summary_result.get("summary"):+ print("Generated summary:\n")+ print(summary_result["summary"])+++'''+Markdown file 'math_planning_summary.md' saved successfully+Summary saved to: context_files/session_20250918_192642_141905/math_planning_summary.md+Generated summary:++- Context+ - User is preparing a math practice worksheet for students.+ - Assistant offered to tailor the worksheet and asked clarifying questions (grade/age, topics, number of problems, answer key vs step-by-step, difficulty, time/layout).++- Key decisions made in conversation+ - Assistant provided a ready-to-use sample worksheet for Grade 6 (mixed skills) with 12 problems and a brief answer key.+ - User requested numerical checks using tools for arithmetic steps.++- Actions performed (completed)+ - Assistant used tools to verify calculations:+ - calculate_add(27, 15) → 42 (reported: 27 + 15 = 42)+ - calculate_multiply(42, 3) → 126 (reported: 42 * 3 = 126)++- Pending action items (who can/should act)+ - Assistant: prepare a customized worksheet based on user preferences (grade/topic/number of problems/difficulty).+ - Assistant: format the worksheet as a printable PDF or Google Doc if requested.+ - Assistant: provide full step-by-step solutions if the user wants them.+ - User: specify preferences (see open questions) so assistant can generate the customized worksheet.++- Open questions / user choices to confirm+ - What grade or age range should the worksheet target?+ - Which topics to include (arithmetic, fractions, decimals, ratios, pre-algebra, algebra, geometry, word problems, etc.)?+ - How many problems total?+ - Answer key only or full step-by-step solutions?+ - Preferred difficulty level (review, mixed, challenge)?+ - Any time limit, point values, or layout/format requirements?+ - Do you want the worksheet as a PDF or Google Doc?++- Next suggested step+ - User provides the preferences above and/or confirms whether to use the provided Grade 6 sample; assistant will generate the customized worksheet (with chosen format and solution detail).+''' # noqa: E501+++if __name__ == "__main__":+ main()