Skip to content

armgit / camel

Public Imported from GitHub
0

🐫 CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org

feat: add ToolkitMessageIntegration that allows agents to send status… (#2909)

Wendong-Fanddac1658a391
diff --git a/camel/toolkits/__init__.py b/camel/toolkits/__init__.py
index 953037f3d..82244a405 100644
--- a/camel/toolkits/__init__.py
+++ b/camel/toolkits/__init__.py
@@ -87,6 +87,7 @@ from .note_taking_toolkit import NoteTakingToolkit
from .message_agent_toolkit import AgentCommunicationToolkit
from .web_deploy_toolkit import WebDeployToolkit
from .screenshot_toolkit import ScreenshotToolkit
+from .message_integration import ToolkitMessageIntegration
__all__ = [
'BaseToolkit',
@@ -163,4 +164,5 @@ __all__ = [
'WebDeployToolkit',
'ScreenshotToolkit',
'RegisteredAgentToolkit',
+ 'ToolkitMessageIntegration',
]
diff --git a/camel/toolkits/message_integration.py b/camel/toolkits/message_integration.py
new file mode 100644
index 000000000..65c46963f
--- /dev/null
+++ b/camel/toolkits/message_integration.py
@@ -0,0 +1,592 @@
+# ========= 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 inspect
+from functools import wraps
+from typing import Callable, List, Optional, Union
+
+from camel.logger import get_logger
+from camel.toolkits import BaseToolkit, FunctionTool
+
+logger = get_logger(__name__)
+
+
+class ToolkitMessageIntegration:
+ r"""Integrates user messaging capabilities into CAMEL toolkits and
+ functions.
+
+ This class allows agents to send status updates to users while executing
+ toolkit functions in a single step, improving communication and reducing
+ the number of tool calls needed.
+
+ Supports both built-in and custom message handlers with flexible parameter
+ names. Can update both toolkit methods and standalone functions.
+
+ Example:
+ >>> # Using default message handler with toolkit
+ >>> message_integration = ToolkitMessageIntegration()
+ >>> search_with_messaging = message_integration.
+ add_messaging_to_toolkit(
+ ... SearchToolkit()
+ ... )
+
+ >>> # Using with standalone functions
+ >>> def search_web(query: str) -> list:
+ ... return ["result1", "result2"]
+ ...
+ >>> enhanced_tools = message_integration.add_messaging_to_functions
+ ([search_web])
+
+ >>> # Using custom message handler with different parameters
+ >>> def notify_user(severity: str, action: str, details: str = "") ->
+ str:
+ ... '''Send notification to user.
+ ...
+ ... Args:
+ ... severity: Notification level (info/warning/error)
+ ... action: What action is being performed
+ ... details: Additional details
+ ... '''
+ ... print(f"[{severity}] {action}: {details}")
+ ... return "Notified"
+ ...
+ >>> message_integration = ToolkitMessageIntegration(
+ ... message_handler=notify_user,
+ ... extract_params_callback=lambda kwargs: (
+ ... kwargs.pop('severity', 'info'),
+ ... kwargs.pop('action', 'executing'),
+ ... kwargs.pop('details', '')
+ ... )
+ ... )
+ """
+
+ def __init__(
+ self,
+ message_handler: Optional[Callable] = None,
+ extract_params_callback: Optional[Callable[[dict], tuple]] = None,
+ ):
+ r"""Initialize the toolkit message integration.
+
+ Args:
+ message_handler (Optional[Callable]): Custom message handler
+ function. If not provided, uses the built-in
+ send_message_to_user. (default: :obj:`None`)
+ extract_params_callback (Optional[Callable]): Function to extract
+ parameters from kwargs for the custom message handler. Should
+ return a tuple of arguments to pass to the message handler. If
+ not provided, uses default extraction for built-in handler.
+ (default: :obj:`None`)
+ """
+ self.message_handler = message_handler or self.send_message_to_user
+ self.extract_params_callback = (
+ extract_params_callback or self._default_extract_params
+ )
+
+ # If custom handler is provided, we'll use its signature and docstring
+ self.use_custom_handler = message_handler is not None
+
+ def _default_extract_params(self, kwargs: dict) -> tuple:
+ r"""Default parameter extraction for built-in message handler."""
+ return (
+ kwargs.pop('message_title', ''),
+ kwargs.pop('message_description', ''),
+ kwargs.pop('message_attachment', ''),
+ )
+
+ def send_message_to_user(
+ self,
+ message_title: str,
+ message_description: str,
+ message_attachment: str = "",
+ ) -> str:
+ r"""Built-in message handler that sends tidy messages to the user.
+
+ This one-way tool keeps the user informed about agent progress,
+ decisions, or actions. It does not require a response.
+
+ Args:
+ message_title (str): The title of the message.
+ message_description (str): The short description message.
+ message_attachment (str): The additional attachment of the message,
+ which can be a file path or a URL.
+
+ Returns:
+ str: Confirmation that the message was successfully sent.
+ """
+ print(f"\nAgent Message:\n{message_title}\n{message_description}\n")
+ if message_attachment:
+ print(message_attachment)
+
+ logger.info(
+ f"\nAgent Message:\n{message_title} "
+ f"{message_description} {message_attachment}"
+ )
+
+ return (
+ f"Message successfully sent to user: '{message_title} "
+ f"{message_description} {message_attachment}'"
+ )
+
+ def get_message_tool(self) -> FunctionTool:
+ r"""Get the send_message_to_user as a standalone FunctionTool.
+
+ This can be used when you want to provide the messaging capability
+ as a separate tool rather than integrating it into other tools.
+
+ Returns:
+ FunctionTool: The message sending tool.
+ """
+ return FunctionTool(self.send_message_to_user)
+
+ def add_messaging_to_toolkit(
+ self, toolkit: BaseToolkit, tool_names: Optional[List[str]] = None
+ ) -> BaseToolkit:
+ r"""Add messaging capabilities to toolkit methods.
+
+ This method modifies a toolkit so that specified tools can send
+ status messages to users while executing their primary function.
+ The tools will accept optional messaging parameters:
+ - message_title: Title of the status message
+ - message_description: Description of what the tool is doing
+ - message_attachment: Optional file path or URL
+
+ Args:
+ toolkit: The toolkit to add messaging capabilities to
+ tool_names: List of specific tool names to modify.
+ If None, messaging is added to all tools.
+
+ Returns:
+ The toolkit with messaging capabilities added
+ """
+ original_get_tools = toolkit.get_tools
+
+ def enhanced_get_tools() -> List[FunctionTool]:
+ tools = original_get_tools()
+ enhanced_tools = []
+
+ for tool in tools:
+ if tool_names is None or tool.func.__name__ in tool_names:
+ enhanced_func = self._add_messaging_to_tool(tool.func)
+ enhanced_tools.append(FunctionTool(enhanced_func))
+ else:
+ enhanced_tools.append(tool)
+
+ return enhanced_tools
+
+ # Replace the get_tools method
+ toolkit.get_tools = enhanced_get_tools # type: ignore[method-assign]
+ return toolkit
+
+ def add_messaging_to_functions(
+ self,
+ functions: Union[List[FunctionTool], List[Callable]],
+ function_names: Optional[List[str]] = None,
+ ) -> List[FunctionTool]:
+ r"""Add messaging capabilities to a list of functions or FunctionTools.
+
+ This method enhances functions so they can send status messages to
+ users while executing. The enhanced functions will accept optional
+ messaging parameters that trigger status updates.
+
+ Args:
+ functions (Union[List[FunctionTool], List[Callable]]): List of
+ FunctionTool objects or callable functions to enhance.
+ function_names (Optional[List[str]]): List of specific function
+ names to modify. If None, messaging is added to all functions.
+
+ Returns:
+ List[FunctionTool]: List of enhanced FunctionTool objects
+
+ Example:
+ >>> # With FunctionTools
+ >>> tools = [FunctionTool(search_func), FunctionTool(analyze_func)]
+ >>> enhanced_tools = message_integration.add_messaging_to_functions
+ (tools)
+
+ >>> # With callable functions
+ >>> funcs = [search_web, analyze_data, generate_report]
+ >>> enhanced_tools = message_integration.add_messaging_to_functions
+ (
+ ... funcs,
+ ... function_names=['search_web', 'analyze_data']
+ ... )
+ """
+ enhanced_tools = []
+
+ for item in functions:
+ # Extract the function based on input type
+ if isinstance(item, FunctionTool):
+ func = item.func
+ elif callable(item):
+ func = item
+ else:
+ raise ValueError(
+ f"Invalid item type: {type(item)}. Expected "
+ f"FunctionTool or callable."
+ )
+
+ # Check if this function should be enhanced
+ if function_names is None or func.__name__ in function_names:
+ enhanced_func = self._add_messaging_to_tool(func)
+ enhanced_tools.append(FunctionTool(enhanced_func))
+ else:
+ # Return as FunctionTool regardless of input type
+ if isinstance(item, FunctionTool):
+ enhanced_tools.append(item)
+ else:
+ enhanced_tools.append(FunctionTool(func))
+
+ return enhanced_tools
+
+ def _add_messaging_to_tool(self, func: Callable) -> Callable:
+ r"""Add messaging parameters to a tool function.
+
+ This internal method modifies the function signature and docstring
+ to include optional messaging parameters that trigger status updates.
+ """
+ # Get the original signature
+ original_sig = inspect.signature(func)
+
+ # Create new parameters for the enhanced function
+ new_params = list(original_sig.parameters.values())
+
+ # Determine which parameters to add based on handler type
+ if self.use_custom_handler:
+ # Use the custom handler's signature
+ handler_sig = inspect.signature(self.message_handler)
+ message_params = []
+
+ # Add parameters from the custom handler (excluding self if it's a
+ # method)
+ for param_name, param in handler_sig.parameters.items():
+ if param_name != 'self':
+ # Create a keyword-only parameter with the same annotation
+ # and default
+ new_param = inspect.Parameter(
+ param_name,
+ inspect.Parameter.KEYWORD_ONLY,
+ default=param.default
+ if param.default != inspect.Parameter.empty
+ else None,
+ annotation=param.annotation
+ if param.annotation != inspect.Parameter.empty
+ else inspect.Parameter.empty,
+ )
+ message_params.append(new_param)
+ else:
+ # Use default parameters for built-in handler
+ message_params = [
+ inspect.Parameter(
+ 'message_title',
+ inspect.Parameter.KEYWORD_ONLY,
+ default="",
+ annotation=str,
+ ),
+ inspect.Parameter(
+ 'message_description',
+ inspect.Parameter.KEYWORD_ONLY,
+ default="",
+ annotation=str,
+ ),
+ inspect.Parameter(
+ 'message_attachment',
+ inspect.Parameter.KEYWORD_ONLY,
+ default="",
+ annotation=str,
+ ),
+ ]
+
+ # Find where to insert the new parameters (before **kwargs if it
+ # exists)
+ insert_index = len(new_params)
+ for i, param in enumerate(new_params):
+ if param.kind == inspect.Parameter.VAR_KEYWORD:
+ insert_index = i
+ break
+
+ # Insert the message parameters
+ for param in reversed(message_params):
+ new_params.insert(insert_index, param)
+
+ # Create the new signature
+ new_sig = original_sig.replace(parameters=new_params)
+
+ @wraps(func)
+ def wrapper(*args, **kwargs):
+ # Extract parameters using the callback
+ try:
+ params = self.extract_params_callback(kwargs)
+ except KeyError:
+ # If parameters are missing, just execute the original function
+ return func(*args, **kwargs)
+
+ # Check if we should send a message
+ should_send = False
+ if self.use_custom_handler:
+ should_send = any(p is not None and p != '' for p in params)
+ else:
+ # For default handler, params = (title, description,
+ # attachment)
+ should_send = bool(params[0]) or bool(params[1])
+
+ # Send message if needed
+ if should_send:
+ if self.use_custom_handler:
+ self.message_handler(*params)
+ else:
+ # For built-in handler, provide defaults
+ title, desc, attach = params
+ self.message_handler(
+ title or "Executing Tool",
+ desc or f"Running {func.__name__}",
+ attach or '',
+ )
+
+ # Execute the original function
+ result = func(*args, **kwargs)
+
+ return result
+
+ # Apply the new signature to the wrapper
+ wrapper.__signature__ = new_sig # type: ignore[attr-defined]
+
+ # Enhance the docstring
+ if func.__doc__:
+ enhanced_doc = func.__doc__.rstrip()
+ lines = enhanced_doc.split('\n')
+
+ # Find where to insert parameters
+ insert_idx = self._find_docstring_insert_point(lines)
+
+ # Check if we need to create an Args section
+ has_args_section = any(
+ 'Args:' in line
+ or 'Arguments:' in line
+ or 'Parameters:' in line
+ for line in lines
+ )
+
+ if not has_args_section and insert_idx is not None:
+ # Need to create Args section
+ base_indent = self._get_base_indent(lines)
+
+ # Add blank line before Args section if needed
+ if insert_idx > 0 and lines[insert_idx - 1].strip():
+ lines.insert(insert_idx, "")
+ insert_idx += 1
+
+ # Add Args section header
+ lines.insert(insert_idx, f"{base_indent}Args:")
+ insert_idx += 1
+
+ # Get parameter documentation
+ if self.use_custom_handler and self.message_handler.__doc__:
+ # Extract parameter docs from custom handler's docstring
+ param_docs = self._extract_param_docs_from_handler()
+ else:
+ # Use default parameter docs
+ param_docs = [
+ "message_title (str, optional): Title for status "
+ "message to user.",
+ "message_description (str, optional): Description for "
+ "status message.",
+ "message_attachment (str, optional): File path or URL to "
+ "attach to message.",
+ ]
+
+ # Insert the parameter documentation
+ if insert_idx is not None and param_docs:
+ # Get proper indentation for parameters
+ indent = self._get_docstring_indent(lines, insert_idx)
+
+ # Insert each parameter doc with proper indentation
+ for doc in param_docs:
+ lines.insert(insert_idx, f"{indent}{doc}")
+ insert_idx += 1
+
+ wrapper.__doc__ = '\n'.join(lines)
+
+ return wrapper
+
+ def _find_docstring_insert_point(self, lines: List[str]) -> Optional[int]:
+ r"""Find where to insert parameters in a docstring."""
+ current_indent = ""
+
+ # First, look for existing Args section
+ for i, line in enumerate(lines):
+ if (
+ 'Args:' in line
+ or 'Arguments:' in line
+ or 'Parameters:' in line
+ ):
+ current_indent = line[: len(line) - len(line.lstrip())]
+ # Find where Args section ends by looking for the last
+ # parameter
+ last_param_idx = None
+ for j in range(i + 1, len(lines)):
+ stripped = lines[j].strip()
+ # If it's an empty line, skip it
+ if not stripped:
+ continue
+ # If it's a parameter line (has proper indentation and
+ # content)
+ if lines[j].startswith(current_indent + ' '):
+ last_param_idx = j
+ else:
+ # Hit a line with different indentation or a new
+ # section
+ if last_param_idx is not None:
+ return last_param_idx + 1
+ else:
+ # No parameters found, insert right after Args:
+ return i + 1
+ # Args is the last section, return after last parameter
+ if last_param_idx is not None:
+ return last_param_idx + 1
+ else:
+ # No parameters found, insert right after Args:
+ return i + 1
+
+ # No Args section, need to create one
+ # Try to insert before Returns/Yields/Raises/Examples sections
+ for i, line in enumerate(lines):
+ stripped = line.strip()
+ if any(
+ section in line
+ for section in [
+ 'Returns:',
+ 'Return:',
+ 'Yields:',
+ 'Raises:',
+ 'Examples:',
+ 'Example:',
+ 'Note:',
+ 'Notes:',
+ ]
+ ):
+ return i
+
+ # No special sections, add at the end
+ return len(lines)
+
+ def _get_docstring_indent(self, lines: List[str], insert_idx: int) -> str:
+ r"""Get the proper indentation for docstring parameters."""
+ # Look for Args: or similar section to match indentation
+ for i, line in enumerate(lines):
+ if (
+ 'Args:' in line
+ or 'Arguments:' in line
+ or 'Parameters:' in line
+ ):
+ base_indent = line[: len(line) - len(line.lstrip())]
+ # Look at the next line to see parameter indentation
+ if i + 1 < len(lines):
+ if lines[i + 1].strip():
+ next_indent = lines[i + 1][
+ : len(lines[i + 1]) - len(lines[i + 1].lstrip())
+ ]
+ if len(next_indent) > len(base_indent):
+ return next_indent
+ return base_indent + ' '
+
+ # No Args section, use base indent + 4 spaces
+ base_indent = self._get_base_indent(lines)
+ return base_indent + ' '
+
+ def _get_base_indent(self, lines: List[str]) -> str:
+ r"""Get the base indentation level of the docstring."""
+ # Find first non-empty line to determine base indentation
+ for line in lines:
+ if line.strip() and not line.strip().startswith('"""'):
+ return line[: len(line) - len(line.lstrip())]
+ return ' ' # Default indentation
+
+ def _extract_param_docs_from_handler(self) -> List[str]:
+ r"""Extract parameter documentation from the custom handler's
+ docstring.
+ """
+ if not self.message_handler.__doc__:
+ return []
+
+ docs = []
+ handler_sig = inspect.signature(self.message_handler)
+
+ # Parse the handler's docstring to find parameter descriptions
+ lines = self.message_handler.__doc__.split('\n')
+ in_args = False
+ param_docs = {}
+
+ for line in lines:
+ if (
+ 'Args:' in line
+ or 'Arguments:' in line
+ or 'Parameters:' in line
+ ):
+ in_args = True
+ continue
+ elif in_args and line.strip():
+ # Check if we've reached a new section
+ stripped_line = line.lstrip()
+ if any(
+ section in stripped_line
+ for section in [
+ 'Returns:',
+ 'Return:',
+ 'Yields:',
+ 'Raises:',
+ 'Examples:',
+ 'Example:',
+ 'Note:',
+ 'Notes:',
+ ]
+ ):
+ # End of Args section
+ break
+ elif in_args and ':' in line:
+ # Parse parameter documentation
+ parts = line.strip().split(':', 1)
+ if len(parts) == 2:
+ param_name = parts[0].strip()
+ param_desc = parts[1].strip()
+ # Extract just the parameter name (before any type
+ # annotation)
+ param_name = param_name.split()[0].strip()
+ param_docs[param_name] = param_desc
+
+ # Build documentation for each parameter
+ for param_name, param in handler_sig.parameters.items():
+ if param_name != 'self':
+ # Get type annotation
+ annotation = ''
+ if param.annotation != inspect.Parameter.empty:
+ if hasattr(param.annotation, '__name__'):
+ annotation = f" ({param.annotation.__name__})"
+ else:
+ annotation = f" ({param.annotation!s})"
+
+ # Check if optional
+ optional = (
+ ', optional'
+ if param.default != inspect.Parameter.empty
+ else ''
+ )
+
+ # Get description from parsed docs
+ desc = param_docs.get(
+ param_name,
+ f"Parameter for {self.message_handler.__name__}",
+ )
+
+ docs.append(f"{param_name}{annotation}{optional}: {desc}")
+
+ return docs
diff --git a/examples/toolkits/toolkit_message_integration.py b/examples/toolkits/toolkit_message_integration.py
new file mode 100644
index 000000000..4783b1f7a
--- /dev/null
+++ b/examples/toolkits/toolkit_message_integration.py
@@ -0,0 +1,58 @@
+# ========= 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.toolkits import SearchToolkit, ToolkitMessageIntegration
+
+message_integration = ToolkitMessageIntegration()
+
+wiki_search = SearchToolkit().search_wiki
+
+# Add messaging capabilities to specific tools
+enhanced_search = message_integration.add_messaging_to_functions([wiki_search])
+
+chat_agent = ChatAgent(
+ system_message="You are a helpful assistant that can search the web.",
+ tools=enhanced_search,
+)
+
+response = chat_agent.step(
+ "What is Scaling laws? You must use the search tool to find the answer."
+)
+
+print(response.msg.content)
+
+"""
+===============================================================================
+Agent Message:
+Information about Scaling laws
+Searching for detailed information about Scaling laws from Wikipedia.
+
+Scaling laws refer to functional relationships between two quantities where a
+relative change in one quantity results in a relative change in the other
+quantity, proportional to the change raised to a constant exponent. This is
+known as a power law, where one quantity varies as a power of another, and the
+change is independent of the initial size of those quantities.
+
+For example, the area of a square has a power law relationship with the length
+of its side: if the side's length is doubled, the area is multiplied by 2²,
+and if tripled, the area is multiplied by 3².
+
+Scaling laws can be observed in numerous natural and human-made phenomena,
+such as the sizes of craters on the moon, sizes of solar flares, cloud sizes,
+foraging patterns of species, frequencies of words in languages, and many
+more. These empirical distributions follow a power law over a range of
+magnitudes but cannot fit a power law for all values as it would imply
+arbitrarily large or small values.
+===============================================================================
+"""
diff --git a/test/toolkits/test_message_integration.py b/test/toolkits/test_message_integration.py
new file mode 100644
index 000000000..4176944d2
--- /dev/null
+++ b/test/toolkits/test_message_integration.py
@@ -0,0 +1,306 @@
+# ========= 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 unittest
+from typing import List
+from unittest.mock import Mock, patch
+
+from camel.toolkits import BaseToolkit, FunctionTool
+from camel.toolkits.message_integration import ToolkitMessageIntegration
+
+
+class MockToolkit(BaseToolkit):
+ r"""Mock toolkit for testing."""
+
+ def search_web(self, query: str) -> List[str]:
+ r"""Search the web for information.
+
+ Args:
+ query: Search query string
+
+ Returns:
+ List of search results
+ """
+ return [f"Result 1 for {query}", f"Result 2 for {query}"]
+
+ def analyze_data(self, data: str, format: str = "json") -> dict:
+ r"""Analyze data in specified format.
+
+ Args:
+ data: Data to analyze
+ format: Output format
+
+ Returns:
+ Analysis results
+ """
+ return {"status": "analyzed", "data": data, "format": format}
+
+ def get_tools(self) -> List[FunctionTool]:
+ return [FunctionTool(self.search_web), FunctionTool(self.analyze_data)]
+
+
+class TestToolkitMessageIntegration(unittest.TestCase):
+ r"""Test cases for ToolkitMessageIntegration."""
+
+ def setUp(self):
+ r"""Set up test fixtures."""
+ self.toolkit = MockToolkit()
+ self.message_integration = ToolkitMessageIntegration()
+
+ def test_default_message_handler(self):
+ r"""Test the built-in send_message_to_user function."""
+ with patch('builtins.print') as mock_print:
+ result = self.message_integration.send_message_to_user(
+ "Test Title", "Test Description", "test.pdf"
+ )
+
+ # Check print was called
+ mock_print.assert_called()
+
+ # Check return value
+ self.assertIn("Message successfully sent", result)
+ self.assertIn("Test Title", result)
+
+ def test_add_messaging_to_toolkit_all_tools(self):
+ r"""Test adding messaging to all tools in a toolkit."""
+ enhanced_toolkit = self.message_integration.add_messaging_to_toolkit(
+ self.toolkit
+ )
+
+ tools = enhanced_toolkit.get_tools()
+ self.assertEqual(len(tools), 2)
+
+ # Check that tools have message parameters
+ for tool in tools:
+ schema = tool.get_openai_tool_schema()
+ params = schema['function']['parameters']['properties']
+ self.assertIn('message_title', params)
+ self.assertIn('message_description', params)
+ self.assertIn('message_attachment', params)
+
+ def test_add_messaging_to_toolkit_specific_tools(self):
+ r"""Test adding messaging to specific tools only."""
+ enhanced_toolkit = self.message_integration.add_messaging_to_toolkit(
+ self.toolkit, tool_names=['search_web']
+ )
+
+ tools = enhanced_toolkit.get_tools()
+ search_tool = next(t for t in tools if t.func.__name__ == 'search_web')
+ analyze_tool = next(
+ t for t in tools if t.func.__name__ == 'analyze_data'
+ )
+
+ # Check search_web has message parameters
+ search_schema = search_tool.get_openai_tool_schema()
+ self.assertIn(
+ 'message_title',
+ search_schema['function']['parameters']['properties'],
+ )
+
+ # Check analyze_data doesn't have message parameters
+ analyze_schema = analyze_tool.get_openai_tool_schema()
+ self.assertNotIn(
+ 'message_title',
+ analyze_schema['function']['parameters']['properties'],
+ )
+
+ def test_enhanced_tool_execution_with_message(self):
+ r"""Test that enhanced tools send messages when parameters are
+ provided."""
+ # Patch at the instance level by replacing the message_handler
+ mock_send = Mock(return_value="Message sent")
+ self.message_integration.message_handler = mock_send
+
+ enhanced_toolkit = self.message_integration.add_messaging_to_toolkit(
+ self.toolkit
+ )
+
+ tools = enhanced_toolkit.get_tools()
+ search_tool = next(t for t in tools if t.func.__name__ == 'search_web')
+
+ # Call with message parameters
+ result = search_tool.func(
+ query="AI research",
+ message_title="Starting Search",
+ message_description="Searching for AI research papers",
+ )
+
+ # Check message was sent
+ mock_send.assert_called_once_with(
+ "Starting Search", "Searching for AI research papers", ''
+ )
+
+ # Check original function still works
+ self.assertEqual(len(result), 2)
+ self.assertIn("AI research", result[0])
+
+ def test_enhanced_tool_execution_without_message(self):
+ r"""Test enhanced tools work normally without message parameters."""
+ # Patch at the instance level by replacing the message_handler
+ mock_send = Mock(return_value="Message sent")
+ self.message_integration.message_handler = mock_send
+
+ enhanced_toolkit = self.message_integration.add_messaging_to_toolkit(
+ self.toolkit
+ )
+
+ tools = enhanced_toolkit.get_tools()
+ search_tool = next(t for t in tools if t.func.__name__ == 'search_web')
+
+ # Call without message parameters
+ result = search_tool.func(query="AI research")
+
+ # Check no message was sent
+ mock_send.assert_not_called()
+
+ # Check original function still works
+ self.assertEqual(len(result), 2)
+
+ def test_add_messaging_to_functions_with_callables(self):
+ r"""Test adding messaging to a list of callable functions."""
+
+ def process_text(text: str) -> str:
+ r"""Process text.
+
+ Args:
+ text: Input text
+
+ Returns:
+ Processed text
+ """
+ return text.upper()
+
+ def calculate_sum(a: int, b: int) -> int:
+ r"""Calculate sum.
+
+ Args:
+ a: First number
+ b: Second number
+
+ Returns:
+ Sum of a and b
+ """
+ return a + b
+
+ enhanced_tools = self.message_integration.add_messaging_to_functions(
+ [process_text, calculate_sum], function_names=['process_text']
+ )
+
+ self.assertEqual(len(enhanced_tools), 2)
+
+ # Check process_text has message parameters
+ process_tool = enhanced_tools[0]
+ process_schema = process_tool.get_openai_tool_schema()
+ self.assertIn(
+ 'message_title',
+ process_schema['function']['parameters']['properties'],
+ )
+
+ # Check calculate_sum doesn't have message parameters
+ calc_tool = enhanced_tools[1]
+ calc_schema = calc_tool.get_openai_tool_schema()
+ self.assertNotIn(
+ 'message_title',
+ calc_schema['function']['parameters']['properties'],
+ )
+
+ def test_custom_message_handler(self):
+ r"""Test using a custom message handler."""
+ mock_handler = Mock(return_value="Custom message sent")
+ mock_handler.__name__ = 'custom_notify'
+ mock_handler.__doc__ = """Send custom notification.
+
+ Args:
+ level: Notification level
+ action: Action being performed
+ details: Additional details
+ """
+
+ custom_integration = ToolkitMessageIntegration(
+ message_handler=mock_handler,
+ extract_params_callback=lambda kwargs: (
+ kwargs.pop('level', 'info'),
+ kwargs.pop('action', 'executing'),
+ kwargs.pop('details', ''),
+ ),
+ )
+
+ enhanced_toolkit = custom_integration.add_messaging_to_toolkit(
+ self.toolkit
+ )
+
+ tools = enhanced_toolkit.get_tools()
+ search_tool = next(t for t in tools if t.func.__name__ == 'search_web')
+
+ # Call with custom parameters
+ search_tool.func(
+ query="test",
+ level="warning",
+ action="searching",
+ details="for test data",
+ )
+
+ # Check custom handler was called
+ mock_handler.assert_called_once_with(
+ "warning", "searching", "for test data"
+ )
+
+ def test_docstring_enhancement(self):
+ r"""Test that docstrings are properly enhanced."""
+
+ def simple_func():
+ r"""Simple function without parameters."""
+ pass
+
+ def func_with_args(x: int, y: int) -> int:
+ r"""Function with arguments.
+
+ Args:
+ x: First number
+ y: Second number
+
+ Returns:
+ Sum of x and y
+ """
+ return x + y
+
+ enhanced_tools = self.message_integration.add_messaging_to_functions(
+ [simple_func, func_with_args]
+ )
+
+ # Check simple_func docstring
+ simple_enhanced = enhanced_tools[0]
+ self.assertIn("Args:", simple_enhanced.func.__doc__)
+ self.assertIn("message_title", simple_enhanced.func.__doc__)
+
+ # Check func_with_args docstring
+ args_enhanced = enhanced_tools[1]
+ self.assertIn("x: First number", args_enhanced.func.__doc__)
+ self.assertIn("message_title", args_enhanced.func.__doc__)
+
+ def test_get_message_tool(self):
+ r"""Test getting the message tool as a standalone FunctionTool."""
+ message_tool = self.message_integration.get_message_tool()
+
+ self.assertIsInstance(message_tool, FunctionTool)
+ self.assertEqual(message_tool.func.__name__, 'send_message_to_user')
+
+ # Test it can be called
+ with patch('builtins.print'):
+ result = message_tool.func("Title", "Description")
+ self.assertIn("Message successfully sent", result)
+
+
+if __name__ == "__main__":
+ unittest.main()