🐫 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: Support share_memory in Workforce (#2631)
Wendong-Fana52d1b74a4ed
diff --git a/camel/societies/workforce/workforce.py b/camel/societies/workforce/workforce.pyindex d7fa6641f..d6d6f5044 100644--- a/camel/societies/workforce/workforce.py+++ b/camel/societies/workforce/workforce.py@@ -90,16 +90,26 @@ class Workforce(BaseNode):for graceful shutdown when a task fails 3 times. During thisperiod, the workforce remains active for debugging.Set to 0 for immediate shutdown. (default: :obj:`15.0`)+ share_memory (bool, optional): Whether to enable shared memory across+ SingleAgentWorker instances in the workforce. When enabled, all+ SingleAgentWorker instances, coordinator agent, and task planning+ agent will share their complete conversation history and+ function-calling trajectory, providing better context for task+ handoffs and continuity. Note: Currently only supports+ SingleAgentWorker instances; RolePlayingWorker and nested+ Workforce instances do not participate in memory sharing.+ (default: :obj:`False`)Example:- >>> # Configure with custom model+ >>> # Configure with custom model and shared memory>>> model = ModelFactory.create(... ModelPlatformType.OPENAI, ModelType.GPT_4O... )>>> workforce = Workforce(... "Research Team",... coordinator_agent_kwargs={"model": model, "token_limit": 4000},- ... task_agent_kwargs={"model": model, "token_limit": 8000}+ ... task_agent_kwargs={"model": model, "token_limit": 8000},+ ... share_memory=True # Enable shared memory... )>>>>>> # Process a task@@ -115,12 +125,14 @@ class Workforce(BaseNode):task_agent_kwargs: Optional[Dict] = None,new_worker_agent_kwargs: Optional[Dict] = None,graceful_shutdown_timeout: float = 15.0,+ share_memory: bool = False,) -> None:super().__init__(description)self._child_listening_tasks: Deque[asyncio.Task] = deque()self._children = children or []self.new_worker_agent_kwargs = new_worker_agent_kwargsself.graceful_shutdown_timeout = graceful_shutdown_timeout+ self.share_memory = share_memory# Warning messages for default model usageif coordinator_agent_kwargs is None:@@ -154,6 +166,13 @@ class Workforce(BaseNode):"available options.")+ if self.share_memory:+ logger.info(+ "Shared memory enabled. All agents will share their complete "+ "conversation history and function-calling trajectory for "+ "better context continuity during task handoffs."+ )+coord_agent_sys_msg = BaseMessage.make_assistant_message(role_name="Workforce Manager",content="You are coordinating a group of workers. A worker can be "@@ -179,6 +198,134 @@ class Workforce(BaseNode):def __repr__(self):return f"Workforce {self.node_id} ({self.description})"+ def _collect_shared_memory(self) -> Dict[str, List]:+ r"""Collect memory from all SingleAgentWorker instances for sharing.++ Returns:+ Dict[str, List]: A dictionary mapping agent types to their memory+ records. Contains entries for 'coordinator', 'task_agent',+ and 'workers'.+ """+ # TODO: add memory collection for RolePlayingWorker and nested+ # Workforce instances+ if not self.share_memory:+ return {}++ shared_memory: Dict[str, List] = {+ 'coordinator': [],+ 'task_agent': [],+ 'workers': [],+ }++ try:+ # Collect coordinator agent memory+ coord_records = self.coordinator_agent.memory.retrieve()+ shared_memory['coordinator'] = [+ record.memory_record.to_dict() for record in coord_records+ ]++ # Collect task agent memory+ task_records = self.task_agent.memory.retrieve()+ shared_memory['task_agent'] = [+ record.memory_record.to_dict() for record in task_records+ ]++ # Collect worker memory only from SingleAgentWorker instances+ for child in self._children:+ if isinstance(child, SingleAgentWorker):+ worker_records = child.worker.memory.retrieve()+ worker_memory = [+ record.memory_record.to_dict()+ for record in worker_records+ ]+ shared_memory['workers'].extend(worker_memory)++ except Exception as e:+ logger.warning(f"Error collecting shared memory: {e}")++ return shared_memory++ def _share_memory_with_agents(+ self, shared_memory: Dict[str, List]+ ) -> None:+ r"""Share collected memory with coordinator, task agent, and+ SingleAgentWorker instances.++ Args:+ shared_memory (Dict[str, List]): Memory records collected from+ all agents to be shared.+ """+ if not self.share_memory or not shared_memory:+ return++ try:+ # Create a consolidated memory from all collected records+ all_records = []+ for _memory_type, records in shared_memory.items():+ all_records.extend(records)++ if not all_records:+ return++ # Import necessary classes for memory record reconstruction+ from camel.memories.records import MemoryRecord++ # Create consolidated memory objects from records+ memory_records = []+ for record_dict in all_records:+ try:+ memory_record = MemoryRecord.from_dict(record_dict)+ memory_records.append(memory_record)+ except Exception as e:+ logger.warning(f"Failed to reconstruct memory record: {e}")+ continue++ if not memory_records:+ return++ # Share with coordinator agent+ for record in memory_records:+ # Only add records from other agents to avoid duplication+ if record.agent_id != self.coordinator_agent.agent_id:+ self.coordinator_agent.memory.write_record(record)++ # Share with task agent+ for record in memory_records:+ if record.agent_id != self.task_agent.agent_id:+ self.task_agent.memory.write_record(record)++ # Share with SingleAgentWorker instances only+ single_agent_workers = [+ child+ for child in self._children+ if isinstance(child, SingleAgentWorker)+ ]++ for worker in single_agent_workers:+ for record in memory_records:+ if record.agent_id != worker.worker.agent_id:+ worker.worker.memory.write_record(record)++ logger.info(+ f"Shared {len(memory_records)} memory records across "+ f"{len(single_agent_workers) + 2} agents in workforce "+ f"{self.node_id}"+ )++ except Exception as e:+ logger.warning(f"Error sharing memory with agents: {e}")++ def _sync_shared_memory(self) -> None:+ r"""Synchronize memory across all agents by collecting and sharing."""+ if not self.share_memory:+ return++ try:+ shared_memory = self._collect_shared_memory()+ self._share_memory_with_agents(shared_memory)+ except Exception as e:+ logger.warning(f"Error synchronizing shared memory: {e}")+def _decompose_task(self, task: Task) -> List[Task]:r"""Decompose the task into subtasks. This method will also set therelationship between the task and its subtasks.@@ -515,6 +662,15 @@ class Workforce(BaseNode):if task.get_depth() >= 3:# Create a new worker node and reassignassignee = self._create_worker_node_for_task(task)++ # Sync shared memory after creating new worker to provide context+ if self.share_memory:+ logger.info(+ f"Syncing shared memory after creating new worker "+ f"{assignee.node_id} for failed task {task.id}"+ )+ self._sync_shared_memory()+await with_timeout_async(self._post_task(task, assignee.node_id),context=f"posting task {task.id} to new worker\@@ -524,6 +680,15 @@ class Workforce(BaseNode):subtasks = self._decompose_task(task)# Insert packets at the head of the queueself._pending_tasks.extendleft(reversed(subtasks))++ # Sync shared memory after task decomposition+ if self.share_memory:+ logger.info(+ f"Syncing shared memory after decomposing failed "+ f"task {task.id}"+ )+ self._sync_shared_memory()+await with_timeout_async(self._post_ready_tasks(),context="posting ready tasks after task failure",@@ -537,6 +702,14 @@ class Workforce(BaseNode):self._channel.archive_task(task.id),context=f"archiving task {task.id}",)++ # Sync shared memory after task completion to share knowledge+ if self.share_memory:+ logger.info(+ f"Syncing shared memory after task {task.id} completion"+ )+ self._sync_shared_memory()+await with_timeout_async(self._post_ready_tasks(),context="posting ready tasks after task completion",@@ -613,6 +786,13 @@ class Workforce(BaseNode):@check_if_running(False)async def start(self) -> None:r"""Start itself and all the child nodes under it."""+ # Sync shared memory at the start to ensure all agents have context+ if self.share_memory:+ logger.info(+ f"Syncing shared memory at workforce {self.node_id} startup"+ )+ self._sync_shared_memory()+for child in self._children:child_listening_task = asyncio.create_task(child.start())self._child_listening_tasks.append(child_listening_task)@@ -652,6 +832,7 @@ class Workforce(BaseNode):task_agent_kwargs={},new_worker_agent_kwargs=self.new_worker_agent_kwargs,graceful_shutdown_timeout=self.graceful_shutdown_timeout,+ share_memory=self.share_memory,)new_instance.task_agent = self.task_agent.clone(with_memory)diff --git a/examples/workforce/workforce_shared_memory_validation.py b/examples/workforce/workforce_shared_memory_validation.pynew file mode 100644index 000000000..34cce0d43--- /dev/null+++ b/examples/workforce/workforce_shared_memory_validation.py@@ -0,0 +1,576 @@+# ========= 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.messages import BaseMessage+from camel.models import ModelFactory+from camel.societies.workforce import Workforce+from camel.types import ModelPlatformType, ModelType+++def create_test_agent(role_name: str, unique_fact: str, model):+ r"""Create a test agent with a unique piece of information."""+ return ChatAgent(+ system_message=BaseMessage.make_assistant_message(+ role_name=role_name,+ content=f"You are {role_name}. You know this unique "+ f"fact: {unique_fact}. Remember all conversations and when asked "+ f"what you know, mention both your unique fact and any "+ f"information learned from others.",+ ),+ model=model,+ )+++def main():+ r"""Run the validation test for shared memory functionality."""+ print("=== Workforce Shared Memory Validation Test ===\n")++ # Create model+ model = ModelFactory.create(+ model_platform=ModelPlatformType.DEFAULT,+ model_type=ModelType.DEFAULT,+ )++ # === TEST SETUP ===+ print("1. Setting up test workforce with shared memory...")++ workforce = Workforce(+ description="Memory Test Workforce",+ coordinator_agent_kwargs={"model": model},+ task_agent_kwargs={"model": model},+ share_memory=True, # Enable shared memory+ graceful_shutdown_timeout=2.0,+ )++ # Create agents with unique information+ agent_alice = create_test_agent(+ "Alice", "Alice knows the secret code is BLUE42", model+ )+ agent_bob = create_test_agent(+ "Bob", "Bob knows the meeting room is 314", model+ )+ agent_charlie = create_test_agent(+ "Charlie", "Charlie knows the deadline is Friday", model+ )++ workforce.add_single_agent_worker("Alice the Coder", agent_alice)+ workforce.add_single_agent_worker("Bob the Manager", agent_bob)+ workforce.add_single_agent_worker("Charlie the Designer", agent_charlie)++ print("✓ Created workforce with 3 agents")+ print(" - Alice knows: secret code BLUE42")+ print(" - Bob knows: meeting room 314")+ print(" - Charlie knows: deadline Friday")++ # === STEP 1: SIMULATE INDIVIDUAL CONVERSATIONS ===+ print("\n2. Having each agent share their unique information...")++ # Alice shares her secret+ print(" Alice sharing secret code...")+ response_alice = agent_alice.step(+ "I need to document that the secret access code for the project "+ "is BLUE42."+ )+ print(f" Alice: {response_alice.msgs[0].content[:80]}...")++ # Bob shares meeting info+ print(" Bob sharing meeting room...")+ response_bob = agent_bob.step(+ "Important update: our team meeting will be in room 314 this week."+ )+ print(f" Bob: {response_bob.msgs[0].content[:80]}...")++ # Charlie shares deadline+ print(" Charlie sharing deadline...")+ response_charlie = agent_charlie.step(+ "Reminder: the project deadline is this Friday, please "+ "plan accordingly."+ )+ print(f" Charlie: {response_charlie.msgs[0].content[:80]}...")++ # === STEP 2: ANALYZE MEMORY BEFORE SHARING ===+ print("\n3. Analyzing memory BEFORE shared memory synchronization...")++ def analyze_agent_memory(agent: ChatAgent, agent_name: str):+ r"""Analyze an agent's memory context and token count."""+ context, token_count = agent.memory.get_context()+ print(f"\n {agent_name} memory analysis:")+ print(f" Token count: {token_count}")+ print(f" Context messages: {len(context)}")+ print(" Context preview:")+ for i, msg in enumerate(context[-2:]): # Show last 2 messages+ role = msg.get('role', 'unknown')+ content = msg.get('content', '')[:80]+ print(f" {i+1}. [{role}] {content}...")+ return token_count, len(context)++ print(" Memory state BEFORE synchronization:")+ alice_tokens_before, alice_msgs_before = analyze_agent_memory(+ agent_alice, "Alice"+ )+ bob_tokens_before, bob_msgs_before = analyze_agent_memory(agent_bob, "Bob")+ charlie_tokens_before, charlie_msgs_before = analyze_agent_memory(+ agent_charlie, "Charlie"+ )++ total_tokens_before = (+ alice_tokens_before + bob_tokens_before + charlie_tokens_before+ )+ print(f"\n TOTAL TOKENS BEFORE SHARING: {total_tokens_before}")++ # === STEP 3: TRIGGER MEMORY SYNCHRONIZATION ===+ print("\n4. Triggering memory synchronization...")+ workforce._sync_shared_memory()+ print("✓ Memory synchronization completed")++ # === STEP 4: ANALYZE MEMORY AFTER SHARING ===+ print("\n5. Analyzing memory AFTER shared memory synchronization...")++ print(" Memory state AFTER synchronization:")+ alice_tokens_after, alice_msgs_after = analyze_agent_memory(+ agent_alice, "Alice"+ )+ bob_tokens_after, bob_msgs_after = analyze_agent_memory(agent_bob, "Bob")+ charlie_tokens_after, charlie_msgs_after = analyze_agent_memory(+ agent_charlie, "Charlie"+ )++ total_tokens_after = (+ alice_tokens_after + bob_tokens_after + charlie_tokens_after+ )+ print(f"\n TOTAL TOKENS AFTER SHARING: {total_tokens_after}")++ # === STEP 5: TOKEN ANALYSIS COMPARISON ===+ print("\n6. Token Analysis Comparison:")+ print(+ f" Alice: {alice_tokens_before} → {alice_tokens_after} "+ f"tokens ({alice_tokens_after - alice_tokens_before:+d})"+ )+ print(+ f" Bob: {bob_tokens_before} → {bob_tokens_after} "+ f"tokens ({bob_tokens_after - bob_tokens_before:+d})"+ )+ print(+ f" Charlie: {charlie_tokens_before} → {charlie_tokens_after} "+ f"tokens ({charlie_tokens_after - charlie_tokens_before:+d})"+ )+ print(+ f" TOTAL: {total_tokens_before} → {total_tokens_after} "+ f"tokens ({total_tokens_after - total_tokens_before:+d})"+ )++ # Calculate sharing efficiency+ tokens_gained_per_agent = (total_tokens_after - total_tokens_before) / 3+ print(+ f"\n Average tokens gained per agent: {tokens_gained_per_agent:.1f}"+ )+ print(+ f" Memory sharing efficiency: "+ f"{(total_tokens_after / total_tokens_before - 1) * 100:.1f}% increase"+ )++ # === STEP 6: CHECK MEMORY CONTENTS ===+ print("\n7. Analyzing shared memory collection...")+ shared_memory = workforce._collect_shared_memory()++ total_records = (+ len(shared_memory.get('coordinator', []))+ + len(shared_memory.get('task_agent', []))+ + len(shared_memory.get('workers', []))+ )++ print(f" Total memory records collected: {total_records}")+ print(+ f" Coordinator records: {len(shared_memory.get('coordinator', []))}"+ )+ print(f" Task agent records: {len(shared_memory.get('task_agent', []))}")+ print(f" Worker records: {len(shared_memory.get('workers', []))}")++ # === STEP 7: TEST CROSS-AGENT MEMORY ACCESS ===+ print("\n8. Testing cross-agent memory access...")++ def test_agent_knowledge(+ agent: ChatAgent,+ agent_name: str,+ should_know_about: list[str],+ ):+ r"""Test what information an agent can recall."""+ print(f"\n Testing {agent_name}'s knowledge:")++ query = (+ "What information do you have access to? Please list any secret "+ "codes, meeting rooms, deadlines, or other important facts you "+ "know about."+ )++ response = agent.step(query)+ content = response.msgs[0].content.lower()++ # Check for specific information+ knows_blue42 = "blue42" in content or "blue 42" in content+ knows_room314 = "314" in content or "room 314" in content+ knows_friday = "friday" in content++ print(f" Knows secret code BLUE42: {'✓' if knows_blue42 else '✗'}")+ print(f" Knows meeting room 314: {'✓' if knows_room314 else '✗'}")+ print(f" Knows deadline Friday: {'✓' if knows_friday else '✗'}")++ # Count how many pieces of information from other agents they know+ other_agent_info = 0+ if agent_name != "Alice" and knows_blue42:+ other_agent_info += 1+ if agent_name != "Bob" and knows_room314:+ other_agent_info += 1+ if agent_name != "Charlie" and knows_friday:+ other_agent_info += 1++ print(f" Cross-agent information access: {other_agent_info}/2")+ print(f" Response preview: {content[:100]}...")++ return other_agent_info, knows_blue42, knows_room314, knows_friday++ # Test each agent's access to shared information+ alice_cross_info, alice_blue, alice_room, alice_friday = (+ test_agent_knowledge(agent_alice, "Alice", ["room314", "friday"])+ )+ bob_cross_info, bob_blue, bob_room, bob_friday = test_agent_knowledge(+ agent_bob, "Bob", ["blue42", "friday"]+ )+ charlie_cross_info, charlie_blue, charlie_room, charlie_friday = (+ test_agent_knowledge(agent_charlie, "Charlie", ["blue42", "room314"])+ )++ # === STEP 8: VALIDATION RESULTS ===+ print("\n9. Validation Results:")++ total_cross_access = alice_cross_info + bob_cross_info + charlie_cross_info+ max_possible_cross_access = (+ 6 # Each agent can know 2 pieces of info from others+ )++ print(+ f" Total cross-agent information access: "+ f"{total_cross_access}/{max_possible_cross_access}"+ )+ print(+ f" Success rate: "+ f"{(total_cross_access/max_possible_cross_access)*100:.1f}%"+ )++ # Determine if shared memory is working+ if total_cross_access >= 3: # At least 50% cross-access+ print(" ✅ SHARED MEMORY IS WORKING!")+ print(+ " Agents can successfully access information from other "+ "agents' conversations."+ )+ elif total_cross_access > 0:+ print(" ⚠️ PARTIAL SUCCESS")+ print(+ " Some cross-agent memory access detected, but not full "+ "sharing."+ )+ else:+ print(" ❌ SHARED MEMORY NOT WORKING")+ print(+ " Agents cannot access information from other "+ "agents' conversations."+ )++ # === STEP 9: COMPARISON WITH NO SHARED MEMORY ===+ print("\n10. Comparison test: Workforce WITHOUT shared memory...")++ workforce_no_memory = Workforce(+ description="Control Group - No Memory Sharing",+ coordinator_agent_kwargs={"model": model},+ task_agent_kwargs={"model": model},+ share_memory=False, # Disable shared memory+ graceful_shutdown_timeout=2.0,+ )++ # Create fresh agents+ agent_alice_2 = create_test_agent(+ "Alice", "Alice knows the secret code is BLUE42", model+ )+ agent_bob_2 = create_test_agent(+ "Bob", "Bob knows the meeting room is 314", model+ )+ agent_charlie_2 = create_test_agent(+ "Charlie", "Charlie knows the deadline is Friday", model+ )++ workforce_no_memory.add_single_agent_worker(+ "Alice the Coder", agent_alice_2+ )+ workforce_no_memory.add_single_agent_worker("Bob the Manager", agent_bob_2)+ workforce_no_memory.add_single_agent_worker(+ "Charlie the Designer", agent_charlie_2+ )++ # Have conversations+ agent_alice_2.step(+ "I need to document that the secret access code for the project "+ "is BLUE42."+ )+ agent_bob_2.step(+ "Important update: our team meeting will be in room 314 this week."+ )+ agent_charlie_2.step(+ "Reminder: the project deadline is this Friday, please "+ "plan accordingly."+ )++ # Test without memory sync+ print(" Testing agents WITHOUT shared memory:")+ alice_cross_2, _, _, _ = test_agent_knowledge(+ agent_alice_2, "Alice", ["room314", "friday"]+ )+ bob_cross_2, _, _, _ = test_agent_knowledge(+ agent_bob_2, "Bob", ["blue42", "friday"]+ )+ charlie_cross_2, _, _, _ = test_agent_knowledge(+ agent_charlie_2, "Charlie", ["blue42", "room314"]+ )++ total_cross_access_2 = alice_cross_2 + bob_cross_2 + charlie_cross_2++ print(+ f"\n Control group cross-agent access: "+ f"{total_cross_access_2}/{max_possible_cross_access}"+ )+ print(+ f" Control group success rate: "+ f"{(total_cross_access_2/max_possible_cross_access)*100:.1f}%"+ )++ # === FINAL CONCLUSION ===+ print("\n11. Final Conclusion:")+ print(+ f" WITH shared memory: "+ f"{total_cross_access}/{max_possible_cross_access} successful accesses"+ )+ print(+ f" WITHOUT shared memory: "+ f"{total_cross_access_2}/{max_possible_cross_access} "+ f"successful accesses"+ )++ if total_cross_access > total_cross_access_2:+ print(" 🎉 VALIDATION SUCCESSFUL!")+ print(+ " Shared memory significantly improves cross-agent "+ "information access."+ )+ elif total_cross_access == total_cross_access_2 and total_cross_access > 0:+ print(" 🤔 INCONCLUSIVE RESULTS")+ print(+ " Both groups show similar performance. May need different "+ "test approach."+ )+ else:+ print(" ⚠️ SHARED MEMORY NEEDS INVESTIGATION")+ print(+ " Control group performed as well or better than shared "+ "memory group."+ )++ print("\n=== Test Complete ===")+++if __name__ == "__main__":+ main()++++"""+===============================================================================+=== Workforce Shared Memory Validation Test ===++1. Setting up test workforce with shared memory...+✓ Created workforce with 3 agents+ - Alice knows: secret code BLUE42+ - Bob knows: meeting room 314+ - Charlie knows: deadline Friday++2. Having each agent share their unique information...+ Alice sharing secret code...+ Alice: Got it! The secret access code for the project is BLUE42. If you+ need help docum...+ Bob sharing meeting room...+ Bob: Thanks for the update! I actually already know that the team meeting+ is in room ...+ Charlie sharing deadline...+ Charlie: Thanks for the reminder! I also know the deadline is Friday, so+ I'll make sure t...++3. Analyzing memory BEFORE shared memory synchronization...+ Memory state BEFORE synchronization:++ Alice memory analysis:+ Token count: 110+ Context messages: 3+ Context preview:+ 1. [user] I need to document that the secret access code for the+ project is BLUE42....+ 2. [assistant] Got it! The secret access code for the project is+ BLUE42. If you need help docum...++ Bob memory analysis:+ Token count: 114+ Context messages: 3+ Context preview:+ 1. [user] Important update: our team meeting will be in room 314 this+ week....+ 2. [assistant] Thanks for the update! I actually already know that the+ team meeting is in room ...++ Charlie memory analysis:+ Token count: 108+ Context messages: 3+ Context preview:+ 1. [user] Reminder: the project deadline is this Friday, please plan+ accordingly....+ 2. [assistant] Thanks for the reminder! I also know the deadline is+ Friday, so I'll make sure t...++ TOTAL TOKENS BEFORE SHARING: 332++4. Triggering memory synchronization...+✓ Memory synchronization completed++5. Analyzing memory AFTER shared memory synchronization...+ Memory state AFTER synchronization:++ Alice memory analysis:+ Token count: 409+ Context messages: 11+ Context preview:+ 1. [user] Reminder: the project deadline is this Friday, please plan+ accordingly....+ 2. [assistant] Thanks for the reminder! I also know the deadline is+ Friday, so I'll make sure t...++ Bob memory analysis:+ Token count: 409+ Context messages: 11+ Context preview:+ 1. [user] Reminder: the project deadline is this Friday, please plan+ accordingly....+ 2. [assistant] Thanks for the reminder! I also know the deadline is+ Friday, so I'll make sure t...++ Charlie memory analysis:+ Token count: 409+ Context messages: 11+ Context preview:+ 1. [user] Reminder: the project deadline is this Friday, please plan+ accordingly....+ 2. [assistant] Thanks for the reminder! I also know the deadline is+ Friday, so I'll make sure t...++ TOTAL TOKENS AFTER SHARING: 1227++6. Token Analysis Comparison:+ Alice: 110 → 409 tokens (+299)+ Bob: 114 → 409 tokens (+295)+ Charlie: 108 → 409 tokens (+301)+ TOTAL: 332 → 1227 tokens (+895)++ Average tokens gained per agent: 298.3+ Memory sharing efficiency: 269.6% increase++7. Analyzing shared memory collection...+ Total memory records collected: 55+ Coordinator records: 11+ Task agent records: 11+ Worker records: 33++8. Testing cross-agent memory access...++ Testing Alice's knowledge:+ Knows secret code BLUE42: ✓+ Knows meeting room 314: ✓+ Knows deadline Friday: ✓+ Cross-agent information access: 2/2+ Response preview: here's what i know so far:++- the secret access code for the project is blue42.+- the team meeting w...++ Testing Bob's knowledge:+ Knows secret code BLUE42: ✓+ Knows meeting room 314: ✓+ Knows deadline Friday: ✓+ Cross-agent information access: 2/2+ Response preview: i know the secret access code for the project is+ blue42.+i know the team meeting will be in room 3...++ Testing Charlie's knowledge:+ Knows secret code BLUE42: ✓+ Knows meeting room 314: ✓+ Knows deadline Friday: ✓+ Cross-agent information access: 2/2+ Response preview: here's what i know so far:++- the secret access code for the project is blue42.+- the team meeting w...++9. Validation Results:+ Total cross-agent information access: 6/6+ Success rate: 100.0%+ ✅ SHARED MEMORY IS WORKING!+ Agents can successfully access information from other agents'+ conversations.++10. Comparison test: Workforce WITHOUT shared memory...++ Testing agents WITHOUT shared memory:++ Testing Alice's knowledge:+ Knows secret code BLUE42: ✓+ Knows meeting room 314: ✗+ Knows deadline Friday: ✗+ Cross-agent information access: 0/2+ Response preview: i know that the secret access code for the project is+ blue42. so far, i haven't been given any information...++ Testing Bob's knowledge:+ Knows secret code BLUE42: ✗+ Knows meeting room 314: ✓+ Knows deadline Friday: ✗+ Cross-agent information access: 0/2+ Response preview: i know the meeting room is 314. additionally, you+ mentioned that our team meeting this week will be ...++ Testing Charlie's knowledge:+ Knows secret code BLUE42: ✗+ Knows meeting room 314: ✗+ Knows deadline Friday: ✓+ Cross-agent information access: 0/2+ Response preview: i know the unique fact that the project deadline is+ this friday. additionally, from our conversation...++ Control group cross-agent access: 0/6+ Control group success rate: 0.0%++11. Final Conclusion:+ WITH shared memory: 6/6 successful accesses+ WITHOUT shared memory: 0/6 successful accesses+ 🎉 VALIDATION SUCCESSFUL!+ Shared memory significantly improves cross-agent information access.++=== Test Complete ===+===============================================================================+"""diff --git a/test/workforce/test_workforce.py b/test/workforce/test_workforce.pyindex 88de3b26c..0de4d81dc 100644--- a/test/workforce/test_workforce.py+++ b/test/workforce/test_workforce.py@@ -17,9 +17,12 @@ from unittest.mock import AsyncMock, MagicMock, patchimport pytest+from camel.agents import ChatAgent+from camel.models import ModelFactoryfrom camel.societies.workforce.task_channel import TaskChannelfrom camel.societies.workforce.workforce import Workforcefrom camel.tasks.task import Task, TaskState+from camel.types import ModelPlatformType, ModelTypefrom camel.utils import with_timeout_async@@ -272,3 +275,127 @@ async def test_multiple_timeout_points():mock_channel.get_returned_task_by_publisher.assert_called_once()# Verify remove_task was called (this is where the timeout occurred)mock_channel.remove_task.assert_called_once_with(mock_task.id)+++def mock_model():+ r"""Create a real model backend for testing"""+ return ModelFactory.create(+ model_platform=ModelPlatformType.OPENAI,+ model_type=ModelType.STUB,+ )+++def mock_agent():+ r"""Create a mock agent with memory functionality"""+ agent = MagicMock(spec=ChatAgent)+ agent.agent_id = "test_agent_id"+ agent.memory = MagicMock()+ agent.memory.get_context.return_value = ([], 0)++ # Mock step method+ response = MagicMock()+ response.msgs = [MagicMock(content="Test response")]+ agent.step.return_value = response+ return agent+++def sample_shared_memory():+ r"""Sample shared memory data for testing"""+ return {+ 'coordinator': [{"role": "user", "content": "Coordinator info"}],+ 'task_agent': [{"role": "user", "content": "Task agent info"}],+ 'workers': [+ {"role": "user", "content": "Agent knows secret code BLUE42"},+ {"role": "user", "content": "Agent knows meeting room 314"},+ ],+ }++[email protected]("share_memory", [True, False])+def test_workforce_initialization(mock_model, share_memory):+ r"""Test workforce initialization with different memory configurations"""+ workforce = Workforce(+ description="Test Workforce",+ coordinator_agent_kwargs={"model": mock_model},+ task_agent_kwargs={"model": mock_model},+ share_memory=share_memory,+ graceful_shutdown_timeout=2.0,+ )++ assert workforce.share_memory == share_memory+ assert workforce.graceful_shutdown_timeout == 2.0+++def test_shared_memory_operations(+ mock_model, mock_agent, sample_shared_memory+):+ r"""Test shared memory collection and synchronization"""+ workforce = Workforce(+ description="Test Workforce",+ coordinator_agent_kwargs={"model": mock_model},+ task_agent_kwargs={"model": mock_model},+ share_memory=True,+ )++ workforce.add_single_agent_worker("TestAgent", mock_agent)++ # Test memory collection and synchronization+ with patch.object(+ workforce, '_collect_shared_memory', return_value=sample_shared_memory+ ):+ with patch.object(+ workforce, '_share_memory_with_agents'+ ) as mock_share:+ workforce._sync_shared_memory()+ mock_share.assert_called_once_with(sample_shared_memory)+++def test_cross_agent_memory_access(mock_model, sample_shared_memory):+ r"""Test cross-agent information access after memory sync"""+ workforce = Workforce(+ description="Test Workforce",+ coordinator_agent_kwargs={"model": mock_model},+ task_agent_kwargs={"model": mock_model},+ share_memory=True,+ )++ # Create agents with cross-knowledge after sync+ agent_alice = MagicMock(spec=ChatAgent)+ agent_alice.agent_id = "alice_id"+ agent_alice.memory = MagicMock()+ agent_alice.memory.get_context.return_value = ([], 0)+ alice_response = MagicMock()+ alice_response.msgs = [+ MagicMock(content="I know secret code BLUE42 and room 314")+ ]+ agent_alice.step.return_value = alice_response++ agent_bob = MagicMock(spec=ChatAgent)+ agent_bob.agent_id = "bob_id"+ agent_bob.memory = MagicMock()+ agent_bob.memory.get_context.return_value = ([], 0)+ bob_response = MagicMock()+ bob_response.msgs = [MagicMock(content="I know room 314 and code BLUE42")]+ agent_bob.step.return_value = bob_response++ workforce.add_single_agent_worker("Alice", agent_alice)+ workforce.add_single_agent_worker("Bob", agent_bob)++ # Simulate memory sync+ with patch.object(+ workforce, '_collect_shared_memory', return_value=sample_shared_memory+ ):+ with patch.object(workforce, '_share_memory_with_agents'):+ workforce._sync_shared_memory()++ # Test that both agents have access to shared information+ query = "What information do you have?"+ alice_content = agent_alice.step(query).msgs[0].content.lower()+ bob_content = agent_bob.step(query).msgs[0].content.lower()++ # Both should know both pieces of information+ for content in [alice_content, bob_content]:+ assert "blue42" in content and "314" in content