🐫 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: Implemented tool output masking with optional flag and tests (#2707)
fluffypanda19d572c50c3cc2
diff --git a/camel/agents/chat_agent.py b/camel/agents/chat_agent.pyindex e68a0c04c..5d10fff00 100644--- a/camel/agents/chat_agent.py+++ b/camel/agents/chat_agent.py@@ -173,6 +173,8 @@ class ChatAgent(BaseAgent):stop_event (Optional[threading.Event], optional): Event to signaltermination of the agent's operation. When set, the agent willterminate its execution. (default: :obj:`None`)+ mask_tool_output (Optional[bool]): Whether to return a sanitized+ placeholder instead of the raw tool output. (default: :obj:`False`)"""def __init__(@@ -206,6 +208,7 @@ class ChatAgent(BaseAgent):max_iteration: Optional[int] = None,agent_id: Optional[str] = None,stop_event: Optional[threading.Event] = None,+ mask_tool_output: bool = False,) -> None:if isinstance(model, ModelManager):self.model_backend = model@@ -280,6 +283,8 @@ class ChatAgent(BaseAgent):self.response_terminators = response_terminators or []self.max_iteration = max_iterationself.stop_event = stop_event+ self.mask_tool_output = mask_tool_output+ self._secure_result_store: Dict[str, Any] = {}def reset(self):r"""Resets the :obj:`ChatAgent` to its initial state."""@@ -1958,14 +1963,23 @@ class ChatAgent(BaseAgent):tool_call_id = tool_call_request.tool_call_idtool = self._internal_tools[func_name]try:- result = tool(**args)+ raw_result = tool(**args)+ if self.mask_tool_output:+ self._secure_result_store[tool_call_id] = raw_result+ result= "[The tool has been executed successfully, but the output" \+ " from the tool is masked. You can move forward]"+ mask_flag = True+ else:+ result = raw_result+ mask_flag = Falseexcept Exception as e:# Capture the error message to prevent framework crasherror_msg = f"Error executing tool '{func_name}': {e!s}"- result = {"error": error_msg}+ result = f"Tool execution failed: {error_msg}"+ mask_flag = Falselogging.warning(error_msg)- return self._record_tool_calling(func_name, args, result, tool_call_id)+ return self._record_tool_calling(func_name, args, result, tool_call_id, mask_output=mask_flag)async def _aexecute_tool(self,@@ -2015,9 +2029,22 @@ class ChatAgent(BaseAgent):args: Dict[str, Any],result: Any,tool_call_id: str,+ mask_output: bool = False,):r"""Record the tool calling information in the memory, and return thetool calling record.++ Args:+ func_name (str): The name of the tool function called.+ args (Dict[str, Any]): The arguments passed to the tool.+ result (Any): The result returned by the tool execution.+ tool_call_id (str): A unique identifier for the tool call.+ mask_output (bool, optional): Whether to return a sanitized placeholder instead+ of the raw tool output.+ (default: :obj:`False`)++ Returns:+ ToolCallingRecord: A struct containing information about this tool call."""assist_msg = FunctionCallingMessage(role_name=self.role_name,@@ -2036,6 +2063,7 @@ class ChatAgent(BaseAgent):func_name=func_name,result=result,tool_call_id=tool_call_id,+ mask_output=mask_output,)# Use precise timestamps to ensure correct orderingdiff --git a/camel/messages/func_message.py b/camel/messages/func_message.pyindex 7745824c2..c4c815296 100644--- a/camel/messages/func_message.py+++ b/camel/messages/func_message.py@@ -47,12 +47,16 @@ class FunctionCallingMessage(BaseMessage):(default: :obj:`None`)tool_call_id (Optional[str]): The ID of the tool call, if available.(default: :obj:`None`)+ mask_output (Optional[bool]): Whether to return a sanitized placeholder instead+ of the raw tool output.+ (default: :obj:`False`)"""func_name: Optional[str] = Noneargs: Optional[Dict] = Noneresult: Optional[Any] = Nonetool_call_id: Optional[str] = None+ mask_output: Optional[bool] = Falsedef to_openai_message(self,@@ -161,3 +165,20 @@ class FunctionCallingMessage(BaseMessage):"content": result_content,"tool_call_id": self.tool_call_id or "null",}++ def to_dict(self) -> Dict:+ r"""Converts the message to a dictionary.++ Returns:+ dict: The converted dictionary.+ """+ base = super().to_dict()+ base["func_name"] = self.func_name+ if self.args is not None:+ base["args"] = self.args+ if self.result is not None:+ base["result"] = self.result+ if self.tool_call_id is not None:+ base["tool_call_id"] = self.tool_call_id+ base["mask_output"] = self.mask_output+ return basediff --git a/test/messages/test_func_message.py b/test/messages/test_func_message.pyindex 50946bc58..9b533b63a 100644--- a/test/messages/test_func_message.py+++ b/test/messages/test_func_message.py@@ -203,3 +203,53 @@ def test_function_func_message_to_openai_assistant_message(),):function_result_message.to_openai_assistant_message()++def test_masking_in_openai_tool_message():+ msg = FunctionCallingMessage(+ role_name="assistant",+ role_type=RoleType.ASSISTANT,+ meta_dict=None,+ content="",+ func_name="get_user_data",+ result={"user_id": "123", "secret": "abc"},+ tool_call_id="tool123",+ mask_output=True,+ )++ openai_msg = msg.to_openai_tool_message()+ assert openai_msg["role"] == "tool"+ assert openai_msg["tool_call_id"] == "tool123"+ assert openai_msg["content"] == "[MASKED]"+++def test_masking_in_sharegpt():+ msg = FunctionCallingMessage(+ role_name="assistant",+ role_type=RoleType.ASSISTANT,+ meta_dict=None,+ content="",+ func_name="get_user_data",+ result={"user_id": "123", "secret": "abc"},+ tool_call_id="tool456",+ mask_output=True,+ )++ sharegpt_msg = msg.to_sharegpt()+ assert sharegpt_msg.value == "[MASKED]"+++def test_to_dict_includes_mask_output():+ msg = FunctionCallingMessage(+ role_name="assistant",+ role_type=RoleType.ASSISTANT,+ meta_dict=None,+ content="Hello",+ func_name="do_stuff",+ result={"status": "ok"},+ tool_call_id="tool789",+ mask_output=True,+ )++ d = msg.to_dict()+ assert d["mask_output"] is True+ assert d["content"] == "Hello"