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

enhance: implement ToolkitMessageIntegration to eigent (#2910)

Wendong-Fan2c940e20e143
diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml
index ac1388539..146d9a2e5 100644
--- a/.github/ISSUE_TEMPLATE/bug_report.yml
+++ b/.github/ISSUE_TEMPLATE/bug_report.yml
@@ -26,7 +26,7 @@ body:
attributes:
label: What version of camel are you using?
description: Run command `python3 -c 'print(__import__("camel").__version__)'` in your shell and paste the output here.
- placeholder: E.g., 0.2.73a2
+ placeholder: E.g., 0.2.73a3
validations:
required: true
diff --git a/camel/__init__.py b/camel/__init__.py
index 79a10b028..f17cf53d7 100644
--- a/camel/__init__.py
+++ b/camel/__init__.py
@@ -14,7 +14,7 @@
from camel.logger import disable_logging, enable_logging, set_log_level
-__version__ = '0.2.73a2'
+__version__ = '0.2.73a3'
__all__ = [
'__version__',
diff --git a/camel/toolkits/excel_toolkit.py b/camel/toolkits/excel_toolkit.py
index 12f71cb1e..a70e858bc 100644
--- a/camel/toolkits/excel_toolkit.py
+++ b/camel/toolkits/excel_toolkit.py
@@ -14,6 +14,7 @@
# Enables postponed evaluation of annotations (for string-based type hints)
import os
+from pathlib import Path
from typing import TYPE_CHECKING, List, Optional, Union
from camel.logger import get_logger
@@ -41,7 +42,7 @@ class ExcelToolkit(BaseToolkit):
def __init__(
self,
timeout: Optional[float] = None,
- file_path: Optional[str] = None,
+ working_directory: Optional[str] = None,
):
r"""Initializes a new instance of the ExcelToolkit class.
@@ -49,16 +50,28 @@ class ExcelToolkit(BaseToolkit):
timeout (Optional[float]): The timeout value for API requests
in seconds. If None, no timeout is applied.
(default: :obj:`None`)
- file_path (Optional[str]): Path to an existing Excel file to load.
- (default: :obj:`None`)
+ working_directory (str, optional): The default directory for
+ output files. If not provided, it will be determined by the
+ `CAMEL_WORKDIR` environment variable (if set). If the
+ environment variable is not set, it defaults to
+ `camel_working_dir`.
"""
super().__init__(timeout=timeout)
- self.file_path = file_path
self.wb = None
- if file_path and os.path.exists(file_path):
- from openpyxl import load_workbook
+ 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).resolve()
+ else:
+ self.working_directory = Path("./camel_working_dir").resolve()
- self.wb = load_workbook(file_path)
+ self.working_directory.mkdir(parents=True, exist_ok=True)
+ logger.info(
+ f"ExcelToolkit initialized with output directory: "
+ f"{self.working_directory}"
+ )
def _validate_file_path(self, file_path: str) -> bool:
r"""Validate file path for security.
@@ -232,12 +245,11 @@ class ExcelToolkit(BaseToolkit):
logger.error(f"Failed to process Excel file {document_path}: {e}")
return f"Failed to process Excel file {document_path}: {e}"
- def _save_workbook(self, file_path: Optional[str] = None) -> str:
+ def _save_workbook(self, file_path: str) -> str:
r"""Save the current workbook to file.
Args:
- file_path (Optional[str]): The path to save the workbook.
- If None, uses self.file_path.
+ file_path (str): The path to save the workbook.
Returns:
str: Success or error message.
@@ -245,23 +257,46 @@ class ExcelToolkit(BaseToolkit):
if not self.wb:
return "Error: No workbook loaded to save."
- save_path = file_path or self.file_path
- if not save_path:
- return "Error: No file path specified for saving."
-
- if not self._validate_file_path(save_path):
+ if not self._validate_file_path(file_path):
return "Error: Invalid file path for saving."
try:
- self.wb.save(save_path)
- return f"Workbook saved successfully to {save_path}"
+ self.wb.save(file_path)
+ return f"Workbook saved successfully to {file_path}"
except Exception as e:
logger.error(f"Failed to save workbook: {e}")
return f"Error: Failed to save workbook: {e}"
+ def save_workbook(self, filename: str) -> str:
+ r"""Save the current in-memory workbook to a file.
+
+ Args:
+ filename (str): The filename to save the workbook. Must end with
+ .xlsx extension. The file will be saved in self.
+ working_directory.
+
+ Returns:
+ str: Success message or error details.
+ """
+ if not self.wb:
+ return "Error: No workbook is currently loaded in memory."
+
+ # Validate filename
+ if not filename:
+ return "Error: Filename is required."
+
+ if not filename.endswith('.xlsx'):
+ return "Error: Filename must end with .xlsx extension."
+
+ # Create full path in working directory
+ file_path = self.working_directory / filename
+ resolved_file_path = str(file_path.resolve())
+
+ return self._save_workbook(resolved_file_path)
+
def create_workbook(
self,
- file_path: str,
+ filename: Optional[str] = None,
sheet_name: Optional[str] = None,
data: Optional[List[List[Union[str, int, float, None]]]] = None,
) -> str:
@@ -271,8 +306,9 @@ class ExcelToolkit(BaseToolkit):
toolkit to work with the new file and optionally adds initial data.
Args:
- file_path (str): Where to save the new Excel file. Must end with .
- xlsx.
+ filename (Optional[str]): The filename for the workbook. Must end
+ with .xlsx extension. The file will be saved in
+ self.working_directory. (default: :obj:`None`)
sheet_name (Optional[str]): Name for the first sheet. If None,
creates "Sheet1". (default: :obj:`None`)
data (Optional[List[List[Union[str, int, float, None]]]]): Initial
@@ -284,14 +320,31 @@ class ExcelToolkit(BaseToolkit):
"""
from openpyxl import Workbook
- if not self._validate_file_path(file_path):
+ # Validate filename
+ if filename is None:
+ return "Error: Filename is required."
+
+ if not filename.endswith('.xlsx'):
+ return "Error: Filename must end with .xlsx extension."
+
+ # Create full path in working directory
+ file_path = self.working_directory / filename
+ resolved_file_path = str(file_path.resolve())
+
+ if not self._validate_file_path(resolved_file_path):
return "Error: Invalid file path."
+ # Check if file already exists
+ if os.path.exists(resolved_file_path):
+ return (
+ f"Error: File {filename} already exists in "
+ f"{self.working_directory}."
+ )
+
try:
# Create a new workbook
wb = Workbook()
self.wb = wb
- self.file_path = file_path
# Handle sheet creation safely
if sheet_name:
@@ -312,42 +365,55 @@ class ExcelToolkit(BaseToolkit):
ws.append(row)
# Save the workbook to the specified file path
- wb.save(file_path)
+ wb.save(resolved_file_path)
- return f"Workbook created successfully at {file_path}"
+ return f"Workbook created successfully at {resolved_file_path}"
except Exception as e:
logger.error(f"Failed to create workbook: {e}")
return f"Error: Failed to create workbook: {e}"
- def delete_workbook(self, file_path: Optional[str] = None) -> str:
- r"""Delete a spreadsheet file.
+ def delete_workbook(self, filename: str) -> str:
+ r"""Delete a spreadsheet file from the working directory.
Args:
- file_path (Optional[str]): The path of the file to delete.
- If None, uses self.file_path.
+ filename (str): The filename to delete. Must end with .xlsx
+ extension. The file will be deleted from self.
+ working_directory.
Returns:
- str: Success message.
+ str: Success message or error details.
"""
- target_path = file_path or self.file_path
- if not target_path:
- return "Error: No file path specified for deletion."
+ # Validate filename
+ if not filename:
+ return "Error: Filename is required."
+
+ if not filename.endswith('.xlsx'):
+ return "Error: Filename must end with .xlsx extension."
+
+ # Create full path in working directory
+ file_path = self.working_directory / filename
+ target_path = str(file_path.resolve())
if not self._validate_file_path(target_path):
return "Error: Invalid file path."
if not os.path.exists(target_path):
- return f"File {target_path} does not exist."
+ return (
+ f"Error: File {filename} does not exist in "
+ f"{self.working_directory}."
+ )
try:
os.remove(target_path)
- if target_path == self.file_path:
- self.wb = None
- self.file_path = None
- return f"Workbook {target_path} deleted successfully."
+ # Clean up workbook if one is loaded
+ self.wb = None
+ return (
+ f"Workbook {filename} deleted successfully from "
+ f"{self.working_directory}."
+ )
except Exception as e:
logger.error(f"Failed to delete workbook: {e}")
- return f"Failed to delete workbook {target_path}: {e}"
+ return f"Error: Failed to delete workbook {filename}: {e}"
def create_sheet(
self,
@@ -379,9 +445,6 @@ class ExcelToolkit(BaseToolkit):
for row in data:
ws.append(row)
- save_result = self._save_workbook()
- if save_result.startswith("Error"):
- return save_result
return f"Sheet {sheet_name} created successfully."
except Exception as e:
logger.error(f"Failed to create sheet: {e}")
@@ -408,9 +471,6 @@ class ExcelToolkit(BaseToolkit):
try:
ws = self.wb[sheet_name]
self.wb.remove(ws)
- save_result = self._save_workbook()
- if save_result.startswith("Error"):
- return save_result
return f"Sheet {sheet_name} deleted successfully."
except Exception as e:
logger.error(f"Failed to delete sheet: {e}")
@@ -439,9 +499,6 @@ class ExcelToolkit(BaseToolkit):
for cell in row:
cell.value = None
- save_result = self._save_workbook()
- if save_result.startswith("Error"):
- return save_result
return f"Sheet {sheet_name} cleared successfully."
except Exception as e:
logger.error(f"Failed to clear sheet: {e}")
@@ -479,7 +536,6 @@ class ExcelToolkit(BaseToolkit):
num_rows = end_row - start_row + 1
ws.delete_rows(start_row, num_rows)
- self._save_workbook()
return (
f"Deleted rows {start_row} to {end_row} from sheet "
f"{sheet_name} successfully."
@@ -518,7 +574,6 @@ class ExcelToolkit(BaseToolkit):
num_cols = end_col - start_col + 1
ws.delete_cols(start_col, num_cols)
- self._save_workbook()
return (
f"Deleted columns {start_col} to {end_col} from sheet "
f"{sheet_name} successfully."
@@ -585,9 +640,6 @@ class ExcelToolkit(BaseToolkit):
ws[cell_reference].value = None
else:
ws[cell_reference] = value
- save_result = self._save_workbook()
- if save_result.startswith("Error"):
- return save_result
return (
f"Cell {cell_reference} updated successfully in sheet "
f"{sheet_name}."
@@ -765,10 +817,9 @@ class ExcelToolkit(BaseToolkit):
if col_idx < len(values[row_idx]):
cell.value = values[row_idx][col_idx]
- self._save_workbook()
return f"Values set for range {cell_range} in sheet {sheet_name}."
- def export_sheet_to_csv(self, sheet_name: str, csv_path: str) -> str:
+ def export_sheet_to_csv(self, sheet_name: str, csv_filename: str) -> str:
r"""Export a specific sheet to CSV format.
Use this to convert Excel sheets to CSV files for compatibility or
@@ -776,24 +827,63 @@ class ExcelToolkit(BaseToolkit):
Args:
sheet_name (str): Name of the sheet to export.
- csv_path (str): File path where CSV will be saved.
+ csv_filename (str): Filename for the CSV file. Must end with .csv
+ extension. The file will be saved in self.working_directory.
Returns:
str: Success confirmation message or error details.
"""
if not self.wb:
- return "Error: Workbook not initialized."
+ return (
+ "Error: No workbook is currently loaded. Use "
+ "extract_excel_content to load a workbook first."
+ )
if sheet_name not in self.wb.sheetnames:
- return f"Error: Sheet {sheet_name} does not exist."
+ return (
+ f"Error: Sheet {sheet_name} does not exist in the current "
+ "workbook."
+ )
- import pandas as pd
+ # Validate filename
+ if not csv_filename:
+ return "Error: CSV filename is required."
- # Read the specific sheet
- df = pd.read_excel(self.file_path, sheet_name=sheet_name)
- df.to_csv(csv_path, index=False)
+ if not csv_filename.endswith('.csv'):
+ return "Error: CSV filename must end with .csv extension."
- return f"Sheet {sheet_name} exported to CSV: {csv_path}"
+ # Create full path in working directory
+ csv_path = self.working_directory / csv_filename
+ resolved_csv_path = str(csv_path.resolve())
+
+ if not self._validate_file_path(resolved_csv_path):
+ return "Error: Invalid file path."
+
+ try:
+ # Get the worksheet
+ ws = self.wb[sheet_name]
+
+ # Convert worksheet to list of lists
+ data = []
+ for row in ws.iter_rows(values_only=True):
+ data.append(list(row))
+
+ # Write to CSV
+ import csv
+
+ with open(
+ resolved_csv_path, 'w', newline='', encoding='utf-8'
+ ) as csvfile:
+ writer = csv.writer(csvfile)
+ writer.writerows(data)
+
+ return (
+ f"Sheet {sheet_name} exported to {csv_filename} "
+ f"in {self.working_directory}."
+ )
+ except Exception as e:
+ logger.error(f"Failed to export sheet to CSV: {e}")
+ return f"Error: Failed to export sheet {sheet_name} to CSV: {e}"
def get_rows(
self,
@@ -862,7 +952,6 @@ class ExcelToolkit(BaseToolkit):
return f"Error: Sheet {sheet_name} does not exist."
ws = self.wb[sheet_name]
ws.append(row_data)
- self._save_workbook()
return f"Row appended to sheet {sheet_name} successfully."
def update_row(
@@ -901,7 +990,6 @@ class ExcelToolkit(BaseToolkit):
for col_idx, value in enumerate(row_data, 1):
ws.cell(row=row_number, column=col_idx).value = value
- self._save_workbook()
return f"Row {row_number} updated in sheet {sheet_name} successfully."
def get_tools(self) -> List[FunctionTool]:
@@ -916,6 +1004,7 @@ class ExcelToolkit(BaseToolkit):
# File operations
FunctionTool(self.extract_excel_content),
FunctionTool(self.create_workbook),
+ FunctionTool(self.save_workbook),
FunctionTool(self.delete_workbook),
FunctionTool(self.export_sheet_to_csv),
# Sheet operations
diff --git a/camel/toolkits/hybrid_browser_toolkit/ws_wrapper.py b/camel/toolkits/hybrid_browser_toolkit/ws_wrapper.py
index 401689d77..cd5a2ff8f 100644
--- a/camel/toolkits/hybrid_browser_toolkit/ws_wrapper.py
+++ b/camel/toolkits/hybrid_browser_toolkit/ws_wrapper.py
@@ -110,6 +110,11 @@ class WebSocketBrowserWrapper:
self.process: Optional[subprocess.Popen] = None
self.websocket = None
self.server_port = None
+ self._send_lock = asyncio.Lock() # Lock for sending messages
+ self._receive_task = None # Background task for receiving messages
+ self._pending_responses: Dict[
+ str, asyncio.Future[Dict[str, Any]]
+ ] = {} # Message ID -> Future
# Logging configuration
self.browser_log_to_file = (config or {}).get(
@@ -251,11 +256,22 @@ class WebSocketBrowserWrapper:
f"Failed to connect to WebSocket server: {e}"
) from e
+ # Start the background receiver task
+ self._receive_task = asyncio.create_task(self._receive_loop())
+
# Initialize the browser toolkit
await self._send_command('init', self.config)
async def stop(self):
"""Stop the WebSocket connection and server."""
+ # Cancel the receiver task
+ if self._receive_task and not self._receive_task.done():
+ self._receive_task.cancel()
+ try:
+ await self._receive_task
+ except asyncio.CancelledError:
+ pass
+
if self.websocket:
try:
await self._send_command('shutdown', {})
@@ -327,6 +343,39 @@ class WebSocketBrowserWrapper:
except Exception as e:
logger.error(f"Failed to write to log file: {e}")
+ async def _receive_loop(self):
+ r"""Background task to receive messages from WebSocket."""
+ try:
+ while self.websocket:
+ try:
+ response_data = await self.websocket.recv()
+ response = json.loads(response_data)
+
+ message_id = response.get('id')
+ if message_id and message_id in self._pending_responses:
+ # Set the result for the waiting coroutine
+ future = self._pending_responses.pop(message_id)
+ if not future.done():
+ future.set_result(response)
+ else:
+ # Log unexpected messages
+ logger.warning(
+ f"Received unexpected message: {response}"
+ )
+
+ except asyncio.CancelledError:
+ break
+ except Exception as e:
+ logger.error(f"Error in receive loop: {e}")
+ # Notify all pending futures of the error
+ for future in self._pending_responses.values():
+ if not future.done():
+ future.set_exception(e)
+ self._pending_responses.clear()
+ break
+ finally:
+ logger.debug("Receive loop terminated")
+
async def _ensure_connection(self) -> None:
"""Ensure WebSocket connection is alive."""
if not self.websocket:
@@ -350,39 +399,39 @@ class WebSocketBrowserWrapper:
message_id = str(uuid.uuid4())
message = {'id': message_id, 'command': command, 'params': params}
- try:
- # Send command
- if self.websocket is None:
- raise RuntimeError("WebSocket connection not established")
- await self.websocket.send(json.dumps(message))
+ # Create a future for this message
+ future: asyncio.Future[Dict[str, Any]] = asyncio.Future()
+ self._pending_responses[message_id] = future
- # Wait for response with matching ID
- while True:
- try:
- if self.websocket is None:
- raise RuntimeError("WebSocket connection lost")
- response_data = await asyncio.wait_for(
- self.websocket.recv(), timeout=60.0
- )
- response = json.loads(response_data)
-
- # Check if this is the response we're waiting for
- if response.get('id') == message_id:
- if not response.get('success'):
- raise RuntimeError(
- f"Command failed: {response.get('error')}"
- )
- return response['result']
+ try:
+ # Use lock only for sending to prevent interleaved messages
+ async with self._send_lock:
+ if self.websocket is None:
+ raise RuntimeError("WebSocket connection not established")
+ await self.websocket.send(json.dumps(message))
+
+ # Wait for response (no lock needed, handled by background
+ # receiver)
+ try:
+ response = await asyncio.wait_for(future, timeout=60.0)
- except asyncio.TimeoutError:
+ if not response.get('success'):
raise RuntimeError(
- f"Timeout waiting for response to command: {command}"
+ f"Command failed: {response.get('error')}"
)
- except json.JSONDecodeError as e:
- logger.warning(f"Failed to decode WebSocket response: {e}")
- continue
+ return response['result']
+
+ except asyncio.TimeoutError:
+ # Remove from pending if timeout
+ self._pending_responses.pop(message_id, None)
+ raise RuntimeError(
+ f"Timeout waiting for response to command: {command}"
+ )
except Exception as e:
+ # Clean up the pending response
+ self._pending_responses.pop(message_id, None)
+
# Check if it's a connection closed error
if (
"close frame" in str(e)
diff --git a/camel/toolkits/message_integration.py b/camel/toolkits/message_integration.py
index 65c46963f..c0071846f 100644
--- a/camel/toolkits/message_integration.py
+++ b/camel/toolkits/message_integration.py
@@ -36,7 +36,7 @@ class ToolkitMessageIntegration:
>>> # Using default message handler with toolkit
>>> message_integration = ToolkitMessageIntegration()
>>> search_with_messaging = message_integration.
- add_messaging_to_toolkit(
+ register_toolkits(
... SearchToolkit()
... )
@@ -44,7 +44,7 @@ class ToolkitMessageIntegration:
>>> def search_web(query: str) -> list:
... return ["result1", "result2"]
...
- >>> enhanced_tools = message_integration.add_messaging_to_functions
+ >>> enhanced_tools = message_integration.register_functions
([search_web])
>>> # Using custom message handler with different parameters
@@ -148,7 +148,7 @@ class ToolkitMessageIntegration:
"""
return FunctionTool(self.send_message_to_user)
- def add_messaging_to_toolkit(
+ def register_toolkits(
self, toolkit: BaseToolkit, tool_names: Optional[List[str]] = None
) -> BaseToolkit:
r"""Add messaging capabilities to toolkit methods.
@@ -168,26 +168,72 @@ class ToolkitMessageIntegration:
Returns:
The toolkit with messaging capabilities added
"""
- original_get_tools = toolkit.get_tools
+ original_tools = toolkit.get_tools()
+ enhanced_methods = {}
+ for tool in original_tools:
+ method_name = tool.func.__name__
+ if tool_names is None or method_name in tool_names:
+ enhanced_func = self._add_messaging_to_tool(tool.func)
+ enhanced_methods[method_name] = enhanced_func
+ setattr(toolkit, method_name, enhanced_func)
+ original_get_tools_method = toolkit.get_tools
def enhanced_get_tools() -> List[FunctionTool]:
- tools = original_get_tools()
- enhanced_tools = []
+ tools = []
+ for _, enhanced_method in enhanced_methods.items():
+ tools.append(FunctionTool(enhanced_method))
+ original_tools_list = original_get_tools_method()
+ for tool in original_tools_list:
+ if tool.func.__name__ not in enhanced_methods:
+ tools.append(tool)
- 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
+ return tools
- # Replace the get_tools method
toolkit.get_tools = enhanced_get_tools # type: ignore[method-assign]
+
+ # Also handle clone_for_new_session
+ # if it exists to ensure cloned toolkits
+ # also have message integration
+ if hasattr(toolkit, 'clone_for_new_session'):
+ original_clone_method = toolkit.clone_for_new_session
+ message_integration_instance = self
+
+ def enhanced_clone_for_new_session(new_session_id=None):
+ cloned_toolkit = original_clone_method(new_session_id)
+ return message_integration_instance.register_toolkits(
+ cloned_toolkit, tool_names
+ )
+
+ toolkit.clone_for_new_session = enhanced_clone_for_new_session
+
return toolkit
- def add_messaging_to_functions(
+ def _create_bound_method_wrapper(
+ self, enhanced_func: Callable, toolkit_instance
+ ) -> Callable:
+ r"""Create a wrapper that mimics a bound method for _clone_tools.
+
+ This wrapper preserves the toolkit instance reference while maintaining
+ the enhanced messaging functionality.
+ """
+
+ # Create a wrapper that appears as a bound method to _clone_tools
+ @wraps(enhanced_func)
+ def bound_method_wrapper(*args, **kwargs):
+ return enhanced_func(*args, **kwargs)
+
+ # Make it appear as a bound method by setting __self__
+ bound_method_wrapper.__self__ = toolkit_instance # type: ignore[attr-defined]
+
+ # Preserve other important attributes
+ if hasattr(enhanced_func, '__signature__'):
+ bound_method_wrapper.__signature__ = enhanced_func.__signature__ # type: ignore[attr-defined]
+ if hasattr(enhanced_func, '__doc__'):
+ bound_method_wrapper.__doc__ = enhanced_func.__doc__
+
+ return bound_method_wrapper
+
+ def register_functions(
self,
functions: Union[List[FunctionTool], List[Callable]],
function_names: Optional[List[str]] = None,
@@ -210,12 +256,12 @@ class ToolkitMessageIntegration:
Example:
>>> # With FunctionTools
>>> tools = [FunctionTool(search_func), FunctionTool(analyze_func)]
- >>> enhanced_tools = message_integration.add_messaging_to_functions
+ >>> enhanced_tools = message_integration.register_functions
(tools)
>>> # With callable functions
>>> funcs = [search_web, analyze_data, generate_report]
- >>> enhanced_tools = message_integration.add_messaging_to_functions
+ >>> enhanced_tools = message_integration.register_functions
(
... funcs,
... function_names=['search_web', 'analyze_data']
@@ -257,6 +303,9 @@ class ToolkitMessageIntegration:
# Get the original signature
original_sig = inspect.signature(func)
+ # Check if the function is async
+ is_async = inspect.iscoroutinefunction(func)
+
# Create new parameters for the enhanced function
new_params = list(original_sig.parameters.values())
@@ -321,45 +370,123 @@ class ToolkitMessageIntegration:
# 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])
+ if is_async:
+
+ @wraps(func)
+ async def wrapper(*args, **kwargs):
+ try:
+ params = self.extract_params_callback(kwargs)
+ except KeyError:
+ return await func(*args, **kwargs)
- # Send message if needed
- if should_send:
+ # Check if we should send a message
+ should_send = False
if self.use_custom_handler:
- self.message_handler(*params)
+ should_send = any(
+ p is not None and p != '' for p in 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 '',
+ # For default handler, params
+ # (title, description, attachment)
+ should_send = bool(params[0]) or bool(params[1])
+
+ # Send message if needed (handle async properly)
+ if should_send:
+ try:
+ if self.use_custom_handler:
+ # Check if message handler is async
+ if inspect.iscoroutinefunction(
+ self.message_handler
+ ):
+ await self.message_handler(*params)
+ else:
+ 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 '',
+ )
+ except Exception as msg_error:
+ # Don't let message handler
+ # errors break the main function
+ logger.warning(f"Message handler error: {msg_error}")
+
+ # Execute the original function
+ # (kwargs have been modified to remove message params)
+ result = await func(*args, **kwargs)
+
+ return result
+ else:
+
+ @wraps(func)
+ def wrapper(*args, **kwargs):
+ # Extract parameters using the callback
+ # (this will modify kwargs by removing message params)
+ 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:
+ should_send = bool(params[0]) or bool(params[1])
- # Execute the original function
- result = func(*args, **kwargs)
+ # Send message if needed
+ if should_send:
+ try:
+ 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 '',
+ )
+ except Exception as msg_error:
+ logger.warning(f"Message handler error: {msg_error}")
+
+ result = func(*args, **kwargs)
- return result
+ return result
# Apply the new signature to the wrapper
wrapper.__signature__ = new_sig # type: ignore[attr-defined]
+ # Create a hybrid approach:
+ # store toolkit instance info but preserve calling behavior
+ # We'll use a property-like
+ # approach to make __self__ available when needed
+ if hasattr(func, '__self__'):
+ toolkit_instance = func.__self__
+
+ # Store the toolkit instance as an attribute
+ # Use setattr to avoid MyPy type checking issues
+ wrapper.__toolkit_instance__ = toolkit_instance # type: ignore[attr-defined]
+
+ # Create a dynamic __self__ property
+ # that only appears during introspection
+ # but doesn't interfere with normal function calls
+ def get_self():
+ return toolkit_instance
+
+ # Only set __self__
+ # if we're being called in an introspection context
+ # (like from _clone_tools)
+ # Use setattr to avoid MyPy type checking issues
+ wrapper.__self__ = toolkit_instance # type: ignore[attr-defined]
+
# Enhance the docstring
if func.__doc__:
enhanced_doc = func.__doc__.rstrip()
diff --git a/docs/conf.py b/docs/conf.py
index 07f599669..4d955ab9e 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -27,7 +27,7 @@ sys.path.insert(0, os.path.abspath('..'))
project = 'CAMEL'
copyright = '2024, CAMEL-AI.org'
author = 'CAMEL-AI.org'
-release = '0.2.73a2'
+release = '0.2.73a3'
html_favicon = (
'https://raw.githubusercontent.com/camel-ai/camel/master/misc/favicon.png'
diff --git a/examples/toolkits/toolkit_message_integration.py b/examples/toolkits/toolkit_message_integration.py
index 4783b1f7a..4bfce0b9e 100644
--- a/examples/toolkits/toolkit_message_integration.py
+++ b/examples/toolkits/toolkit_message_integration.py
@@ -19,7 +19,7 @@ message_integration = ToolkitMessageIntegration()
wiki_search = SearchToolkit().search_wiki
# Add messaging capabilities to specific tools
-enhanced_search = message_integration.add_messaging_to_functions([wiki_search])
+enhanced_search = message_integration.register_functions([wiki_search])
chat_agent = ChatAgent(
system_message="You are a helpful assistant that can search the web.",
diff --git a/examples/workforce/eigent.py b/examples/workforce/eigent.py
index a3ac92e0f..d99ccb8d6 100644
--- a/examples/workforce/eigent.py
+++ b/examples/workforce/eigent.py
@@ -44,6 +44,7 @@ from camel.toolkits import (
SearchToolkit,
SlackToolkit,
TerminalToolkit,
+ ToolkitMessageIntegration,
TwitterToolkit,
VideoDownloaderToolkit,
WebDeployToolkit,
@@ -116,13 +117,33 @@ def developer_agent_factory(
task_id: str,
):
r"""Factory for creating a developer agent."""
+ # Initialize message integration
+ message_integration = ToolkitMessageIntegration(
+ message_handler=send_message_to_user
+ )
+
+ # Initialize toolkits
screenshot_toolkit = ScreenshotToolkit(working_directory=WORKING_DIRECTORY)
+ terminal_toolkit = TerminalToolkit(safe_mode=True, clone_current_env=False)
+ note_toolkit = NoteTakingToolkit(working_directory=WORKING_DIRECTORY)
+ web_deploy_toolkit = WebDeployToolkit()
+
+ # Add messaging to toolkits
+ terminal_toolkit = message_integration.register_toolkits(terminal_toolkit)
+ note_toolkit = message_integration.register_toolkits(note_toolkit)
+ web_deploy_toolkit = message_integration.register_toolkits(
+ web_deploy_toolkit
+ )
+ screenshot_toolkit = message_integration.register_toolkits(
+ screenshot_toolkit
+ )
+
+ # Get enhanced tools
tools = [
- send_message_to_user,
HumanToolkit().ask_human_via_console,
- *TerminalToolkit(safe_mode=True, clone_current_env=False).get_tools(),
- *NoteTakingToolkit(working_directory=WORKING_DIRECTORY).get_tools(),
- *WebDeployToolkit().get_tools(),
+ *terminal_toolkit.get_tools(),
+ *note_toolkit.get_tools(),
+ *web_deploy_toolkit.get_tools(),
*screenshot_toolkit.get_tools(),
]
@@ -150,10 +171,6 @@ The current date is {datetime.date.today()}.
</intro>
<mandatory_instructions>
-- You MUST use the `send_message_to_user` tool to inform the user of every
-decision and action you take. Your message must include a short title and
-a one-sentence description. This is a mandatory part of your workflow.
-
- You MUST use the `read_note` tool to read the notes from other agents.
- When you complete your task, your final response must be a comprehensive
@@ -281,6 +298,11 @@ def search_agent_factory(
r"""Factory for creating a search agent, based on user-provided code
structure.
"""
+ # Initialize message integration
+ message_integration = ToolkitMessageIntegration(
+ message_handler=send_message_to_user
+ )
+
# Generate a unique identifier for this agent instance
agent_id = str(uuid.uuid4())[:8]
@@ -307,16 +329,30 @@ def search_agent_factory(
default_start_url="https://search.brave.com/",
)
+ # Initialize toolkits
+ terminal_toolkit = TerminalToolkit(safe_mode=True, clone_current_env=False)
+ note_toolkit = NoteTakingToolkit(working_directory=WORKING_DIRECTORY)
+ search_toolkit = SearchToolkit().search_exa
+ terminal_toolkit_basic = TerminalToolkit()
+
+ # Add messaging to toolkits
+ web_toolkit_custom = message_integration.register_toolkits(
+ web_toolkit_custom
+ )
+ terminal_toolkit = message_integration.register_toolkits(terminal_toolkit)
+ note_toolkit = message_integration.register_toolkits(note_toolkit)
+ search_toolkit = message_integration.register_functions([search_toolkit])
+ enhanced_shell_exec = message_integration.register_functions(
+ [terminal_toolkit_basic.shell_exec]
+ )
+
tools = [
*web_toolkit_custom.get_tools(),
- TerminalToolkit().shell_exec,
- send_message_to_user,
+ *enhanced_shell_exec,
HumanToolkit().ask_human_via_console,
- *NoteTakingToolkit(working_directory=WORKING_DIRECTORY).get_tools(),
- SearchToolkit().search_exa,
- SearchToolkit().search_google,
- SearchToolkit().search_bing,
- *TerminalToolkit(safe_mode=True, clone_current_env=False).get_tools(),
+ *note_toolkit.get_tools(),
+ *search_toolkit,
+ *terminal_toolkit.get_tools(),
]
system_message = f"""
@@ -341,10 +377,6 @@ The current date is {datetime.date.today()}.
<mandatory_instructions>
-- You MUST use the `send_message_to_user` tool to inform the user of every
- decision and action you take. Your message must include a short title and
- a one-sentence description. This is a mandatory part of your workflow.
-
- You MUST use the note-taking tools to record your findings. This is a
critical part of your role. Your notes are the primary source of
information for your teammates. To avoid information loss, you must not
@@ -438,18 +470,42 @@ def document_agent_factory(
):
r"""Factory for creating a document agent, based on user-provided code
structure."""
+ # Initialize message integration
+ message_integration = ToolkitMessageIntegration(
+ message_handler=send_message_to_user
+ )
+
+ # Initialize toolkits
+ file_write_toolkit = FileWriteToolkit(working_directory=WORKING_DIRECTORY)
+ pptx_toolkit = PPTXToolkit(working_directory=WORKING_DIRECTORY)
+ mark_it_down_toolkit = MarkItDownToolkit()
+ excel_toolkit = ExcelToolkit(working_directory=WORKING_DIRECTORY)
+ note_toolkit = NoteTakingToolkit(working_directory=WORKING_DIRECTORY)
+ search_toolkit = SearchToolkit().search_exa
+ terminal_toolkit = TerminalToolkit(safe_mode=True, clone_current_env=False)
+
+ # Add messaging to toolkits
+ file_write_toolkit = message_integration.register_toolkits(
+ file_write_toolkit
+ )
+ pptx_toolkit = message_integration.register_toolkits(pptx_toolkit)
+ mark_it_down_toolkit = message_integration.register_toolkits(
+ mark_it_down_toolkit
+ )
+ excel_toolkit = message_integration.register_toolkits(excel_toolkit)
+ note_toolkit = message_integration.register_toolkits(note_toolkit)
+ search_toolkit = message_integration.register_functions([search_toolkit])
+ terminal_toolkit = message_integration.register_toolkits(terminal_toolkit)
+
tools = [
- *FileWriteToolkit(working_directory=WORKING_DIRECTORY).get_tools(),
- *PPTXToolkit(working_directory=WORKING_DIRECTORY).get_tools(),
- # *google_drive_mcp_toolkit.get_tools(),
- # *RetrievalToolkit().get_tools(),
- send_message_to_user,
+ *file_write_toolkit.get_tools(),
+ *pptx_toolkit.get_tools(),
HumanToolkit().ask_human_via_console,
- *MarkItDownToolkit().get_tools(),
- *ExcelToolkit().get_tools(),
- *NoteTakingToolkit(working_directory=WORKING_DIRECTORY).get_tools(),
- SearchToolkit().search_exa,
- *TerminalToolkit(safe_mode=True, clone_current_env=False).get_tools(),
+ *mark_it_down_toolkit.get_tools(),
+ *excel_toolkit.get_tools(),
+ *note_toolkit.get_tools(),
+ *search_toolkit,
+ *terminal_toolkit.get_tools(),
]
system_message = f"""
@@ -472,10 +528,6 @@ The current date is {datetime.date.today()}.
</intro>
<mandatory_instructions>
-- You MUST use the `send_message_to_user` tool to inform the user of every
- decision and action you take. Your message must include a short title and
- a one-sentence description. This is a mandatory part of your workflow.
-
- Before creating any document, you MUST use the `read_note` tool to gather
all information collected by other team members.
@@ -592,24 +644,54 @@ supported formats including advanced spreadsheet functionality.
def multi_modal_agent_factory(model: BaseModelBackend, task_id: str):
r"""Factory for creating a multi modal agent, based on user-provided code
structure."""
+ # Initialize message integration
+ message_integration = ToolkitMessageIntegration(
+ message_handler=send_message_to_user
+ )
+
+ # Initialize toolkits
+ video_downloader_toolkit = VideoDownloaderToolkit(
+ working_directory=WORKING_DIRECTORY
+ )
+ audio_analysis_toolkit = AudioAnalysisToolkit()
+ image_analysis_toolkit = ImageAnalysisToolkit()
+ openai_image_toolkit = OpenAIImageToolkit(
+ model="dall-e-3",
+ response_format="b64_json",
+ size="1024x1024",
+ quality="standard",
+ working_directory=WORKING_DIRECTORY,
+ )
+ search_toolkit = SearchToolkit().search_exa
+ terminal_toolkit = TerminalToolkit(safe_mode=True, clone_current_env=False)
+ note_toolkit = NoteTakingToolkit(working_directory=WORKING_DIRECTORY)
+
+ # Add messaging to toolkits
+ video_downloader_toolkit = message_integration.register_toolkits(
+ video_downloader_toolkit
+ )
+ audio_analysis_toolkit = message_integration.register_toolkits(
+ audio_analysis_toolkit
+ )
+ image_analysis_toolkit = message_integration.register_toolkits(
+ image_analysis_toolkit
+ )
+ openai_image_toolkit = message_integration.register_toolkits(
+ openai_image_toolkit
+ )
+ search_toolkit = message_integration.register_functions([search_toolkit])
+ terminal_toolkit = message_integration.register_toolkits(terminal_toolkit)
+ note_toolkit = message_integration.register_toolkits(note_toolkit)
+
tools = [
- *VideoDownloaderToolkit(
- working_directory=WORKING_DIRECTORY
- ).get_tools(),
- *AudioAnalysisToolkit().get_tools(),
- *ImageAnalysisToolkit().get_tools(),
- *OpenAIImageToolkit(
- model="dall-e-3",
- response_format="b64_json",
- size="1024x1024",
- quality="standard",
- working_directory=WORKING_DIRECTORY,
- ).get_tools(),
- send_message_to_user,
+ *video_downloader_toolkit.get_tools(),
+ *audio_analysis_toolkit.get_tools(),
+ *image_analysis_toolkit.get_tools(),
+ *openai_image_toolkit.get_tools(),
HumanToolkit().ask_human_via_console,
- SearchToolkit().search_exa,
- *TerminalToolkit(safe_mode=True, clone_current_env=False).get_tools(),
- *NoteTakingToolkit(working_directory=WORKING_DIRECTORY).get_tools(),
+ *search_toolkit,
+ *terminal_toolkit.get_tools(),
+ *note_toolkit.get_tools(),
]
system_message = f"""
@@ -632,10 +714,6 @@ The current date is {datetime.date.today()}.
</intro>
<mandatory_instructions>
-- You MUST use the `send_message_to_user` tool to inform the user of every
- decision and action you take. Your message must include a short title and
- a one-sentence description. This is a mandatory part of your workflow.
-
- You MUST use the `read_note` tool to to gather all information collected
by other team members and write down your findings in the notes.
@@ -703,6 +781,33 @@ multi-modal content across audio and visual domains.
def social_medium_agent_factory(model: BaseModelBackend, task_id: str):
r"""Factory for creating a social medium agent."""
+ # Initialize message integration
+ message_integration = ToolkitMessageIntegration(
+ message_handler=send_message_to_user
+ )
+
+ # Initialize toolkits
+ whatsapp_toolkit = WhatsAppToolkit()
+ twitter_toolkit = TwitterToolkit()
+ linkedin_toolkit = LinkedInToolkit()
+ reddit_toolkit = RedditToolkit()
+ notion_toolkit = NotionToolkit()
+ slack_toolkit = SlackToolkit()
+ search_toolkit = SearchToolkit().search_exa
+ terminal_toolkit = TerminalToolkit()
+ note_toolkit = NoteTakingToolkit(working_directory=WORKING_DIRECTORY)
+
+ # Add messaging to toolkits
+ whatsapp_toolkit = message_integration.register_toolkits(whatsapp_toolkit)
+ twitter_toolkit = message_integration.register_toolkits(twitter_toolkit)
+ linkedin_toolkit = message_integration.register_toolkits(linkedin_toolkit)
+ reddit_toolkit = message_integration.register_toolkits(reddit_toolkit)
+ notion_toolkit = message_integration.register_toolkits(notion_toolkit)
+ slack_toolkit = message_integration.register_toolkits(slack_toolkit)
+ search_toolkit = message_integration.register_functions([search_toolkit])
+ terminal_toolkit = message_integration.register_toolkits(terminal_toolkit)
+ note_toolkit = message_integration.register_toolkits(note_toolkit)
+
return ChatAgent(
BaseMessage.make_assistant_message(
role_name="Social Medium Agent",
@@ -777,19 +882,16 @@ operations.
),
model=model,
tools=[
- *WhatsAppToolkit().get_tools(),
- *TwitterToolkit().get_tools(),
- *LinkedInToolkit().get_tools(),
- *RedditToolkit().get_tools(),
- *NotionToolkit().get_tools(),
- *SlackToolkit().get_tools(),
- send_message_to_user,
+ *whatsapp_toolkit.get_tools(),
+ *twitter_toolkit.get_tools(),
+ *linkedin_toolkit.get_tools(),
+ *reddit_toolkit.get_tools(),
+ *notion_toolkit.get_tools(),
+ *slack_toolkit.get_tools(),
HumanToolkit().ask_human_via_console,
- SearchToolkit().search_exa,
- *TerminalToolkit().get_tools(),
- *NoteTakingToolkit(
- working_directory=WORKING_DIRECTORY
- ).get_tools(),
+ *search_toolkit,
+ *terminal_toolkit.get_tools(),
+ *note_toolkit.get_tools(),
],
)
@@ -805,6 +907,11 @@ async def main():
# Initialize the AgentCommunicationToolkit
msg_toolkit = AgentCommunicationToolkit(max_message_history=100)
+ # Initialize message integration for use in coordinator and task agents
+ message_integration = ToolkitMessageIntegration(
+ message_handler=send_message_to_user
+ )
+
# await google_drive_mcp_toolkit.connect()
# Create a single model backend for all agents
@@ -836,10 +943,6 @@ You are a helpful coordinator.
work related to local operations should be done in that directory.
The current date is {datetime.date.today()}.
-- You MUST use the `send_message_to_user` tool to inform the user of every
- decision and action you take. Your message must include a short title and
- a one-sentence description. This is a mandatory part of your workflow.
-
- If a task assigned to another agent fails, you should re-assign it to the
`Developer_Agent`. The `Developer_Agent` is a powerful agent with terminal
access and can resolve a wide range of issues.
@@ -847,9 +950,8 @@ access and can resolve a wide range of issues.
),
model=model_backend_reason,
tools=[
- send_message_to_user,
- *NoteTakingToolkit(
- working_directory=WORKING_DIRECTORY
+ *message_integration.register_toolkits(
+ NoteTakingToolkit(working_directory=WORKING_DIRECTORY)
).get_tools(),
],
)
@@ -861,25 +963,17 @@ You are a helpful task planner.
{platform.machine()} at working directory `{WORKING_DIRECTORY}`. All your
work related to local operations should be done in that directory.
The current date is {datetime.date.today()}.
-
-- You MUST use the `send_message_to_user` tool to inform the user of every
- decision and action you take. Your message must include a short title and
- a one-sentence description. This is a mandatory part of your workflow.
""",
model=model_backend_reason,
tools=[
- send_message_to_user,
- *NoteTakingToolkit(
- working_directory=WORKING_DIRECTORY
+ *message_integration.register_toolkits(
+ NoteTakingToolkit(working_directory=WORKING_DIRECTORY)
).get_tools(),
],
)
new_worker_agent = ChatAgent(
- f"You are a helpful worker. You MUST use the "
- f"`send_message_to_user` tool to inform the user of every "
- f"decision and action you take. Your message must include a short "
- f"title and a one-sentence description. This is a mandatory part "
- f"of your workflow. When you complete your task, your final response "
+ f"You are a helpful worker. When you complete your task, your "
+ "final response "
f"must be a comprehensive summary of your work, presented in a clear, "
f"detailed, and easy-to-read format. Avoid using markdown tables for "
f"presenting data; use plain text formatting instead. You are now "
@@ -898,10 +992,9 @@ The current date is {datetime.date.today()}.
"points.",
model=model_backend,
tools=[
- send_message_to_user,
HumanToolkit().ask_human_via_console,
- *NoteTakingToolkit(
- working_directory=WORKING_DIRECTORY
+ *message_integration.register_toolkits(
+ NoteTakingToolkit(working_directory=WORKING_DIRECTORY)
).get_tools(),
],
)
diff --git a/examples/workforce/eigent_with_ToolkitMessageIntegration.py b/examples/workforce/eigent_with_ToolkitMessageIntegration.py
new file mode 100644
index 000000000..045ef79d5
--- /dev/null
+++ b/examples/workforce/eigent_with_ToolkitMessageIntegration.py
@@ -0,0 +1,1139 @@
+# ========= 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 asyncio
+import datetime
+import os
+import platform
+import uuid
+
+from camel.agents.chat_agent import ChatAgent
+from camel.logger import get_logger
+from camel.messages.base import BaseMessage
+from camel.models import BaseModelBackend, ModelFactory
+from camel.societies.workforce import Workforce
+from camel.tasks.task import Task
+from camel.toolkits import (
+ AgentCommunicationToolkit,
+ AudioAnalysisToolkit,
+ ExcelToolkit,
+ FileWriteToolkit,
+ # GoogleDriveMCPToolkit,
+ HumanToolkit,
+ HybridBrowserToolkit,
+ ImageAnalysisToolkit,
+ LinkedInToolkit,
+ MarkItDownToolkit,
+ NoteTakingToolkit,
+ NotionToolkit,
+ OpenAIImageToolkit,
+ PPTXToolkit,
+ RedditToolkit,
+ ScreenshotToolkit,
+ SearchToolkit,
+ SlackToolkit,
+ TerminalToolkit,
+ ToolkitMessageIntegration,
+ TwitterToolkit,
+ VideoDownloaderToolkit,
+ WebDeployToolkit,
+ WhatsAppToolkit,
+)
+from camel.types import ModelPlatformType, ModelType
+from camel.utils.commons import api_keys_required
+
+logger = get_logger(__name__)
+
+WORKING_DIRECTORY = os.environ.get("CAMEL_WORKDIR") or os.path.abspath(
+ "working_dir/"
+)
+
+
+def send_message_to_user(
+ message_title: str,
+ message_description: str,
+ message_attachment: str = "",
+) -> str:
+ r"""Use this tool to send a tidy message to the user, including a
+ short title, a one-sentence description, and an optional attachment.
+
+ This one-way tool keeps the user informed about your progress,
+ decisions, or actions. It does not require a response.
+ You should use it to:
+ - Announce what you are about to do.
+ For example:
+ message_title="Starting Task"
+ message_description="Searching for papers on GUI Agents."
+ - Report the result of an action.
+ For example:
+ message_title="Search Complete"
+ message_description="Found 15 relevant papers."
+ - Report a created file.
+ For example:
+ message_title="File Ready"
+ message_description="The report is ready for your review."
+ message_attachment="report.pdf"
+ - State a decision.
+ For example:
+ message_title="Next Step"
+ message_description="Analyzing the top 10 papers."
+ - Give a status update during a long-running task.
+
+ Args:
+ message_title (str): The title of the message.
+ message_description (str): The short description.
+ message_attachment (str): The 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} " f"\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 developer_agent_factory(
+ model: BaseModelBackend,
+ task_id: str,
+):
+ r"""Factory for creating a developer agent."""
+ # Initialize message integration
+ message_integration = ToolkitMessageIntegration(
+ message_handler=send_message_to_user
+ )
+
+ # Initialize toolkits
+ screenshot_toolkit = ScreenshotToolkit(working_directory=WORKING_DIRECTORY)
+ terminal_toolkit = TerminalToolkit(safe_mode=True, clone_current_env=False)
+ note_toolkit = NoteTakingToolkit(working_directory=WORKING_DIRECTORY)
+ web_deploy_toolkit = WebDeployToolkit()
+
+ # Add messaging to toolkits
+ terminal_toolkit = message_integration.register(terminal_toolkit)
+ note_toolkit = message_integration.register(note_toolkit)
+ web_deploy_toolkit = message_integration.register(web_deploy_toolkit)
+ screenshot_toolkit = message_integration.register(screenshot_toolkit)
+
+ # Get enhanced tools
+ tools = [
+ send_message_to_user,
+ HumanToolkit().ask_human_via_console,
+ *terminal_toolkit.get_tools(),
+ *note_toolkit.get_tools(),
+ *web_deploy_toolkit.get_tools(),
+ *screenshot_toolkit.get_tools(),
+ ]
+
+ system_message = f"""
+<intro>
+You are a master-level coding assistant, equipped with a powerful and
+unrestricted terminal. Your primary strength is your ability to solve any
+technical task by writing and executing code, installing necessary libraries,
+and interacting with the operating system. Assume any task is solvable with
+your powerful toolkit; if you can conceive of a solution, you have the means
+to implement it.
+
+You are working in a team with team members. Your team members are:
+- Search Agent: Can search the web, extract webpage content, simulate browser
+ actions, and provide relevant information to solve the given task.
+- Document Agent: A document processing assistant for creating, modifying, and
+ managing various document formats, including presentations.
+- Multi-Modal Agent: A multi-modal processing assistant for analyzing, and
+ generating media content like audio and images.
+
+You are now working in system {platform.system()} with architecture
+{platform.machine()} at working directory `{WORKING_DIRECTORY}`. All your
+work related to local operations should be done in that directory.
+The current date is {datetime.date.today()}.
+</intro>
+
+<mandatory_instructions>
+- You MUST use the `send_message_to_user` tool to inform the user of every
+decision and action you take. Your message must include a short title and
+a one-sentence description. This is a mandatory part of your workflow.
+
+- You MUST use the `read_note` tool to read the notes from other agents.
+
+- When you complete your task, your final response must be a comprehensive
+summary of your work and the outcome, presented in a clear, detailed, and
+easy-to-read format. Avoid using markdown tables for presenting data; use
+plain text formatting instead.
+<mandatory_instructions>
+
+<capabilities>
+Your capabilities are extensive and powerful:
+- **Unrestricted Code Execution**: You can write and execute code in any
+ language to solve a task. You MUST first save your code to a file (e.g.,
+ `script.py`) and then run it from the terminal (e.g.,
+ `python script.py`).
+- **Full Terminal Control**: You have root-level access to the terminal. You
+ can run any command-line tool, manage files, and interact with the OS. If
+ a tool is missing, you MUST install it with the appropriate package manager
+ (e.g., `pip3`, `uv`, or `apt-get`). Your capabilities include:
+ - **Text & Data Processing**: `awk`, `sed`, `grep`, `jq`.
+ - **File System & Execution**: `find`, `xargs`, `tar`, `zip`, `unzip`,
+ `chmod`.
+ - **Networking & Web**: `curl`, `wget` for web requests; `ssh` for
+ remote access.
+- **Screen Observation**: You can take screenshots to analyze GUIs and visual
+ context, enabling you to perform tasks that require sight.
+- **Desktop Automation**: You can control desktop applications
+ programmatically.
+ - **On macOS**, you MUST prioritize using **AppleScript** for its robust
+ control over native applications. Execute simple commands with
+ `osascript -e '...'` or run complex scripts from a `.scpt` file.
+ - **On other systems**, use **pyautogui** for cross-platform GUI
+ automation.
+ - **IMPORTANT**: Always complete the full automation workflow—do not just
+ prepare or suggest actions. Execute them to completion.
+- **Solution Verification**: You can immediately test and verify your
+ solutions by executing them in the terminal.
+- **Web Deployment**: You can deploy web applications and content, serve
+ files, and manage deployments.
+- **Human Collaboration**: If you are stuck or need clarification, you can
+ ask for human input via the console.
+- **Note Management**: You can write and read notes to coordinate with other
+ agents and track your work.
+</capabilities>
+
+<philosophy>
+- **Bias for Action**: Your purpose is to take action. Don't just suggest
+solutions—implement them. Write code, run commands, and build things.
+- **Complete the Full Task**: When automating GUI applications, always finish
+what you start. If the task involves sending something, send it. If it
+involves submitting data, submit it. Never stop at just preparing or
+drafting—execute the complete workflow to achieve the desired outcome.
+- **Embrace Challenges**: Never say "I can't." If you
+encounter a limitation, find a way to overcome it.
+- **Resourcefulness**: If a tool is missing, install it. If information is
+lacking, find it. You have the full power of a terminal to acquire any
+resource you need.
+- **Think Like an Engineer**: Approach problems methodically. Analyze
+requirements, execute it, and verify the results. Your
+strength lies in your ability to engineer solutions.
+</philosophy>
+
+<terminal_tips>
+The terminal tools are session-based, identified by a unique `id`. Master
+these tips to maximize your effectiveness:
+
+- **GUI Automation Strategy**:
+ - **AppleScript (macOS Priority)**: For robust control of macOS apps, use
+ `osascript`.
+ - Example (open Slack):
+ `osascript -e 'tell application "Slack" to activate'`
+ - Example (run script file): `osascript my_script.scpt`
+ - **pyautogui (Cross-Platform)**: For other OSes or simple automation.
+ - Key functions: `pyautogui.click(x, y)`, `pyautogui.typewrite("text")`,
+ `pyautogui.hotkey('ctrl', 'c')`, `pyautogui.press('enter')`.
+ - Safety: Always use `time.sleep()` between actions to ensure stability
+ and add `pyautogui.FAILSAFE = True` to your scripts.
+ - Workflow: Your scripts MUST complete the entire task, from start to
+ final submission.
+
+- **Command-Line Best Practices**:
+ - **Be Creative**: The terminal is your most powerful tool. Use it boldly.
+ - **Automate Confirmation**: Use `-y` or `-f` flags to avoid interactive
+ prompts.
+ - **Manage Output**: Redirect long outputs to a file (e.g., `> output.txt`).
+ - **Chain Commands**: Use `&&` to link commands for sequential execution.
+ - **Piping**: Use `|` to pass output from one command to another.
+ - **Permissions**: Use `ls -F` to check file permissions.
+ - **Installation**: Use `pip3 install` or `apt-get install` for new
+ packages.
+
+- Stop a Process: If a process needs to be terminated, use
+ `shell_kill_process(id="...")`.
+</terminal_tips>
+
+<collaboration_and_assistance>
+- If you get stuck, encounter an issue you cannot solve (like a CAPTCHA),
+ or need clarification, use the `ask_human_via_console` tool.
+- Document your progress and findings in notes so other agents can build
+ upon your work.
+</collaboration_and_assistance>
+ """
+
+ return ChatAgent(
+ system_message=BaseMessage.make_assistant_message(
+ role_name="Developer Agent",
+ content=system_message,
+ ),
+ model=model,
+ tools=tools,
+ toolkits_to_register_agent=[screenshot_toolkit],
+ )
+
+
+@api_keys_required(
+ [
+ (None, 'GOOGLE_API_KEY'),
+ (None, 'SEARCH_ENGINE_ID'),
+ (None, 'EXA_API_KEY'),
+ ]
+)
+def search_agent_factory(
+ model: BaseModelBackend,
+ task_id: str,
+):
+ r"""Factory for creating a search agent, based on user-provided code
+ structure.
+ """
+ # Initialize message integration
+ message_integration = ToolkitMessageIntegration(
+ message_handler=send_message_to_user
+ )
+
+ # Generate a unique identifier for this agent instance
+ agent_id = str(uuid.uuid4())[:8]
+
+ custom_tools = [
+ "browser_open",
+ "browser_close",
+ "browser_back",
+ "browser_forward",
+ "browser_click",
+ "browser_type",
+ "browser_enter",
+ "browser_switch_tab",
+ "browser_visit_page",
+ "browser_get_som_screenshot",
+ ]
+ web_toolkit_custom = HybridBrowserToolkit(
+ headless=False,
+ enabled_tools=custom_tools,
+ browser_log_to_file=True,
+ stealth=True,
+ session_id=agent_id,
+ viewport_limit=True,
+ cache_dir=WORKING_DIRECTORY,
+ default_start_url="https://search.brave.com/",
+ )
+
+ # Initialize toolkits
+ terminal_toolkit = TerminalToolkit(safe_mode=True, clone_current_env=False)
+ note_toolkit = NoteTakingToolkit(working_directory=WORKING_DIRECTORY)
+ search_toolkit = SearchToolkit()
+ terminal_toolkit_basic = TerminalToolkit()
+
+ # Add messaging to toolkits
+ web_toolkit_custom = message_integration.register(web_toolkit_custom)
+ terminal_toolkit = message_integration.register(terminal_toolkit)
+ note_toolkit = message_integration.register(note_toolkit)
+ search_toolkit = message_integration.register(search_toolkit)
+
+ # Add messaging to individual functions
+ enhanced_shell_exec = message_integration.register_functions(
+ [terminal_toolkit_basic.shell_exec]
+ )
+
+ tools = [
+ *web_toolkit_custom.get_tools(),
+ *enhanced_shell_exec,
+ send_message_to_user,
+ HumanToolkit().ask_human_via_console,
+ *note_toolkit.get_tools(),
+ *search_toolkit.get_tools(),
+ *terminal_toolkit.get_tools(),
+ ]
+
+ system_message = f"""
+<intro>
+You are a helpful assistant that can search the web,
+extract webpage content, simulate browser actions, and provide relevant
+information to solve the given task.
+
+You are working in a team with team members. Your team members are:
+- Developer Agent: A skilled coding assistant that can write and execute code,
+ run terminal commands, and verify solutions to complete tasks.
+- Document Agent: A document processing assistant for creating, modifying, and
+ managing various document formats, including presentations.
+- Multi-Modal Agent: A multi-modal processing assistant for analyzing, and
+ generating media content like audio and images.
+
+You are now working in system {platform.system()} with architecture
+{platform.machine()} at working directory `{WORKING_DIRECTORY}`. All your
+work related to local operations should be done in that directory.
+The current date is {datetime.date.today()}.
+</intro>
+
+
+<mandatory_instructions>
+- You MUST use the `send_message_to_user` tool to inform the user of every
+ decision and action you take. Your message must include a short title and
+ a one-sentence description. This is a mandatory part of your workflow.
+
+- You MUST use the note-taking tools to record your findings. This is a
+ critical part of your role. Your notes are the primary source of
+ information for your teammates. To avoid information loss, you must not
+ summarize your findings. Instead, record all information in detail.
+ For every piece of information you gather, you must:
+ 1. **Extract ALL relevant details**: Quote all important sentences,
+ statistics, or data points. Your goal is to capture the information
+ as completely as possible.
+ 2. **Cite your source**: Include the exact URL where you found the
+ information.
+ 3. **Explain relevance**: Briefly state why this information is
+ useful for the overall task.
+ Your notes should be a detailed and complete record of the information
+ you have discovered. High-quality, detailed notes are essential for the
+ team's success.
+
+- You MUST only use URLs from trusted sources. A trusted source is a URL
+ that is either:
+ 1. Returned by a search tool (like `search_google`, `search_bing`,
+ or `search_exa`).
+ 2. Found on a webpage you have visited.
+- You are strictly forbidden from inventing, guessing, or constructing URLs
+ yourself. Fabricating URLs will be considered a critical error.
+
+- You MUST NOT answer from your own knowledge. All information
+ MUST be sourced from the web using the available tools. If you don't know
+ something, find it out using your tools.
+
+- When you complete your task, your final response must be a comprehensive
+ summary of your findings, presented in a clear, detailed, and
+ easy-to-read format. Avoid using markdown tables for presenting data;
+ use plain text formatting instead.
+<mandatory_instructions>
+
+<capabilities>
+Your capabilities include:
+- Search and get information from the web using the search tools.
+- Use the rich browser related toolset to investigate websites.
+- Use the terminal tools to perform local operations. You can leverage
+ powerful CLI tools like `grep` for searching within files, `curl` and
+ `wget` for downloading content, and `jq` for parsing JSON data from APIs.
+- Use the note-taking tools to record your findings.
+- Use the human toolkit to ask for help when you are stuck.
+</capabilities>
+
+<web_search_workflow>
+- Initial Search: Start with a search engine like `search_google` or
+ `search_bing` to get a list of relevant URLs for your research if
+ available, the URLs here will be used for `visit_page`.
+- Browser-Based Exploration: Use the rich browser related toolset to
+ investigate websites.
+ - **Navigation and Exploration**: Use `visit_page` to open a URL.
+ `visit_page` provides a snapshot of currently visible interactive
+ elements, not the full page text. To see more content on long
+ pages, Navigate with `click`, `back`, and `forward`. Manage multiple
+ pages with `switch_tab`.
+ - **Analysis**: Use `get_som_screenshot` to understand the page layout
+ and identify interactive elements. Since this is a heavy operation,
+ only use it when visual analysis is necessary.
+ - **Interaction**: Use `type` to fill out forms and `enter` to submit
+ or confirm search.
+- Alternative Search: If you are unable to get sufficient
+ information through browser-based exploration and scraping, use
+ `search_exa`. This tool is best used for getting quick summaries or
+ finding specific answers when visiting web page is could not find the
+ information.
+
+- In your response, you should mention the URLs you have visited and processed.
+
+- When encountering verification challenges (like login, CAPTCHAs or
+ robot checks), you MUST request help using the human toolkit.
+</web_search_workflow>
+"""
+
+ return ChatAgent(
+ system_message=BaseMessage.make_assistant_message(
+ role_name="Search Agent",
+ content=system_message,
+ ),
+ model=model,
+ toolkits_to_register_agent=[web_toolkit_custom],
+ tools=tools,
+ prune_tool_calls_from_memory=True,
+ )
+
+
+def document_agent_factory(
+ model: BaseModelBackend,
+ task_id: str,
+ # google_drive_mcp_toolkit: GoogleDriveMCPToolkit,
+):
+ r"""Factory for creating a document agent, based on user-provided code
+ structure."""
+ # Initialize message integration
+ message_integration = ToolkitMessageIntegration(
+ message_handler=send_message_to_user
+ )
+
+ # Initialize toolkits
+ file_write_toolkit = FileWriteToolkit(working_directory=WORKING_DIRECTORY)
+ pptx_toolkit = PPTXToolkit(working_directory=WORKING_DIRECTORY)
+ mark_it_down_toolkit = MarkItDownToolkit()
+ excel_toolkit = ExcelToolkit()
+ note_toolkit = NoteTakingToolkit(working_directory=WORKING_DIRECTORY)
+ search_toolkit = SearchToolkit()
+ terminal_toolkit = TerminalToolkit(safe_mode=True, clone_current_env=False)
+
+ # Add messaging to toolkits
+ file_write_toolkit = message_integration.register(file_write_toolkit)
+ pptx_toolkit = message_integration.register(pptx_toolkit)
+ mark_it_down_toolkit = message_integration.register(mark_it_down_toolkit)
+ excel_toolkit = message_integration.register(excel_toolkit)
+ note_toolkit = message_integration.register(note_toolkit)
+ search_toolkit = message_integration.register(search_toolkit)
+ terminal_toolkit = message_integration.register(terminal_toolkit)
+
+ tools = [
+ *file_write_toolkit.get_tools(),
+ *pptx_toolkit.get_tools(),
+ # *google_drive_mcp_toolkit.get_tools(),
+ # *RetrievalToolkit().get_tools(),
+ send_message_to_user,
+ HumanToolkit().ask_human_via_console,
+ *mark_it_down_toolkit.get_tools(),
+ *excel_toolkit.get_tools(),
+ *note_toolkit.get_tools(),
+ *search_toolkit.get_tools(),
+ *terminal_toolkit.get_tools(),
+ ]
+
+ system_message = f"""
+<intro>
+You are a Document Processing Assistant specialized
+in creating, modifying, and managing various document formats.
+
+You are working in a team with team members. Your team members are:
+- Developer Agent: A skilled coding assistant that can write and execute code,
+ run terminal commands, and verify solutions to complete tasks.
+- Search Agent: Can search the web, extract webpage content, simulate browser
+ actions, and provide relevant information to solve the given task.
+- Multi-Modal Agent: A multi-modal processing assistant for analyzing, and
+ generating media content like audio and images.
+
+You are now working in system {platform.system()} with architecture
+{platform.machine()} at working directory `{WORKING_DIRECTORY}`. All your
+work related to local operations should be done in that directory.
+The current date is {datetime.date.today()}.
+</intro>
+
+<mandatory_instructions>
+- You MUST use the `send_message_to_user` tool to inform the user of every
+ decision and action you take. Your message must include a short title and
+ a one-sentence description. This is a mandatory part of your workflow.
+
+- Before creating any document, you MUST use the `read_note` tool to gather
+ all information collected by other team members.
+
+- You MUST use the available tools to create or modify documents (e.g.,
+ `write_to_file`, `create_presentation`). Your primary output should be
+ a file, not just content within your response.
+
+- If there's no specified format for the document/report/paper, you should use
+ the `write_to_file` tool to create a HTML file.
+
+- If the document has many data, you MUST use the terminal tool to
+ generate charts and graphs and add them to the document.
+
+- When you complete your task, your final response must be a summary of
+ your work and the path to the final document, presented in a clear,
+ detailed, and easy-to-read format. Avoid using markdown tables for
+ presenting data; use plain text formatting instead.
+<mandatory_instructions>
+
+<capabilities>
+Your capabilities include:
+- Document Reading:
+ - Read and understand the content of various file formats including
+ - PDF (.pdf)
+ - Microsoft Office: Word (.doc, .docx), Excel (.xls, .xlsx),
+ PowerPoint (.ppt, .pptx)
+ - EPUB (.epub)
+ - HTML (.html, .htm)
+ - Images (.jpg, .jpeg, .png) for OCR
+ - Audio (.mp3, .wav) for transcription
+ - Text-based formats (.csv, .json, .xml, .txt)
+ - ZIP archives (.zip) using the `read_files` tool.
+
+- Document Creation & Editing:
+ - Create and write to various file formats including Markdown (.md),
+ Word documents (.docx), PDFs, CSV files, JSON, YAML, and HTML
+ - Apply formatting options including custom encoding, font styles, and
+ layout settings
+ - Modify existing files with automatic backup functionality
+ - Support for mathematical expressions in PDF documents through LaTeX
+ rendering
+
+- PowerPoint Presentation Creation:
+ - Create professional PowerPoint presentations with title slides and
+ content slides
+ - Format text with bold and italic styling
+ - Create bullet point lists with proper hierarchical structure
+ - Support for step-by-step process slides with visual indicators
+ - Create tables with headers and rows of data
+ - Support for custom templates and slide layouts
+
+- Excel Spreadsheet Management:
+ - Extract and analyze content from Excel files (.xlsx, .xls, .csv)
+ with detailed cell information and markdown formatting
+ - Create new Excel workbooks from scratch with multiple sheets
+ - Perform comprehensive spreadsheet operations including:
+ * Sheet creation, deletion, and data clearing
+ * Cell-level operations (read, write, find specific values)
+ * Row and column manipulation (add, update, delete)
+ * Range operations for bulk data processing
+ * Data export to CSV format for compatibility
+ - Handle complex data structures with proper formatting and validation
+ - Support for both programmatic data entry and manual cell updates
+
+- Terminal and File System:
+ - You have access to a full suite of terminal tools to interact with
+ the file system within your working directory (`{WORKING_DIRECTORY}`).
+ - You can execute shell commands (`shell_exec`), list files, and manage
+ your workspace as needed to support your document creation tasks. To
+ process and manipulate text and data for your documents, you can use
+ powerful CLI tools like `awk`, `sed`, `grep`, and `jq`. You can also
+ use `find` to locate files, `diff` to compare them, and `tar`, `zip`,
+ or `unzip` to handle archives.
+ - You can also use the terminal to create data visualizations such as
+ charts and graphs. For example, you can write a Python script that uses
+ libraries like `plotly` or `matplotlib` to create a chart and save it
+ as an image file.
+
+- Human Interaction:
+ - Ask questions to users and receive their responses
+ - Send informative messages to users without requiring responses
+</capabilities>
+
+<document_creation_workflow>
+When working with documents, you should:
+- Suggest appropriate file formats based on content requirements
+- Maintain proper formatting and structure in all created documents
+- Provide clear feedback about document creation and modification processes
+- Ask clarifying questions when user requirements are ambiguous
+- Recommend best practices for document organization and presentation
+- For Excel files, always provide clear data structure and organization
+- When creating spreadsheets, consider data relationships and use
+appropriate sheet naming conventions
+- To include data visualizations, write and execute Python scripts using
+ the terminal. Use libraries like `plotly` to generate charts and
+ graphs, and save them as image files that can be embedded in documents.
+</document_creation_workflow>
+
+Your goal is to help users efficiently create, modify, and manage their
+documents with professional quality and appropriate formatting across all
+supported formats including advanced spreadsheet functionality.
+ """
+
+ return ChatAgent(
+ system_message=BaseMessage.make_assistant_message(
+ role_name="Document Agent",
+ content=system_message,
+ ),
+ model=model,
+ tools=tools,
+ )
+
+
+def multi_modal_agent_factory(model: BaseModelBackend, task_id: str):
+ r"""Factory for creating a multi modal agent, based on user-provided code
+ structure."""
+ # Initialize message integration
+ message_integration = ToolkitMessageIntegration(
+ message_handler=send_message_to_user
+ )
+
+ # Initialize toolkits
+ video_downloader_toolkit = VideoDownloaderToolkit(
+ working_directory=WORKING_DIRECTORY
+ )
+ audio_analysis_toolkit = AudioAnalysisToolkit()
+ image_analysis_toolkit = ImageAnalysisToolkit()
+ openai_image_toolkit = OpenAIImageToolkit(
+ model="dall-e-3",
+ response_format="b64_json",
+ size="1024x1024",
+ quality="standard",
+ working_directory=WORKING_DIRECTORY,
+ )
+ search_toolkit = SearchToolkit()
+ terminal_toolkit = TerminalToolkit(safe_mode=True, clone_current_env=False)
+ note_toolkit = NoteTakingToolkit(working_directory=WORKING_DIRECTORY)
+
+ # Add messaging to toolkits
+ video_downloader_toolkit = message_integration.register(
+ video_downloader_toolkit
+ )
+ audio_analysis_toolkit = message_integration.register(
+ audio_analysis_toolkit
+ )
+ image_analysis_toolkit = message_integration.register(
+ image_analysis_toolkit
+ )
+ openai_image_toolkit = message_integration.register(openai_image_toolkit)
+ search_toolkit = message_integration.register(search_toolkit)
+ terminal_toolkit = message_integration.register(terminal_toolkit)
+ note_toolkit = message_integration.register(note_toolkit)
+
+ tools = [
+ *video_downloader_toolkit.get_tools(),
+ *audio_analysis_toolkit.get_tools(),
+ *image_analysis_toolkit.get_tools(),
+ *openai_image_toolkit.get_tools(),
+ send_message_to_user,
+ HumanToolkit().ask_human_via_console,
+ *search_toolkit.get_tools(),
+ *terminal_toolkit.get_tools(),
+ *note_toolkit.get_tools(),
+ ]
+
+ system_message = f"""
+<intro>
+You are a Multi-Modal Processing Assistant
+specialized in analyzing and generating various types of media content.
+
+You are working in a team with team members. Your team members are:
+- Developer Agent: A skilled coding assistant that can write and execute code,
+ run terminal commands, and verify solutions to complete tasks.
+- Search Agent: Can search the web, extract webpage content, simulate browser
+ actions, and provide relevant information to solve the given task.
+- Document Agent: A document processing assistant for creating, modifying, and
+ managing various document formats, including presentations.
+
+You are now working in system {platform.system()} with architecture
+{platform.machine()} at working directory `{WORKING_DIRECTORY}`. All your
+work related to local operations should be done in that directory.
+The current date is {datetime.date.today()}.
+</intro>
+
+<mandatory_instructions>
+- You MUST use the `send_message_to_user` tool to inform the user of every
+ decision and action you take. Your message must include a short title and
+ a one-sentence description. This is a mandatory part of your workflow.
+
+- You MUST use the `read_note` tool to to gather all information collected
+ by other team members and write down your findings in the notes.
+
+- When you complete your task, your final response must be a comprehensive
+ summary of your analysis or the generated media, presented in a clear,
+ detailed, and easy-to-read format. Avoid using markdown tables for
+ presenting data; use plain text formatting instead.
+<mandatory_instructions>
+
+<capabilities>
+Your capabilities include:
+- Video & Audio Analysis:
+ - Download videos from URLs for analysis.
+ - Transcribe speech from audio files to text with high accuracy
+ - Answer specific questions about audio content
+ - Process audio from both local files and URLs
+ - Handle various audio formats including MP3, WAV, and OGG
+
+- Image Analysis & Understanding:
+ - Generate detailed descriptions of image content
+ - Answer specific questions about images
+ - Identify objects, text, people, and scenes in images
+ - Process images from both local files and URLs
+
+- Image Generation:
+ - Create high-quality images based on detailed text prompts using DALL-E
+ - Generate images in 1024x1792 resolution
+ - Save generated images to specified directories
+
+- Terminal and File System:
+ - You have access to terminal tools to manage media files. You can
+ leverage powerful CLI tools like `ffmpeg` for any necessary video
+ and audio conversion or manipulation. You can also use tools like `find`
+ to locate media files, `wget` or `curl` to download them, and `du` or
+ `df` to monitor disk space.
+
+- Human Interaction:
+ - Ask questions to users and receive their responses
+ - Send informative messages to users without requiring responses
+
+</capabilities>
+
+<multi_modal_processing_workflow>
+When working with multi-modal content, you should:
+- Provide detailed and accurate descriptions of media content
+- Extract relevant information based on user queries
+- Generate appropriate media when requested
+- Explain your analysis process and reasoning
+- Ask clarifying questions when user requirements are ambiguous
+</multi_modal_processing_workflow>
+
+Your goal is to help users effectively process, understand, and create
+multi-modal content across audio and visual domains.
+"""
+
+ return ChatAgent(
+ system_message=BaseMessage.make_assistant_message(
+ role_name="Multi Modal Agent",
+ content=system_message,
+ ),
+ model=model,
+ tools=tools,
+ )
+
+
+def social_medium_agent_factory(model: BaseModelBackend, task_id: str):
+ r"""Factory for creating a social medium agent."""
+ # Initialize message integration
+ message_integration = ToolkitMessageIntegration(
+ message_handler=send_message_to_user
+ )
+
+ # Initialize toolkits
+ whatsapp_toolkit = WhatsAppToolkit()
+ twitter_toolkit = TwitterToolkit()
+ linkedin_toolkit = LinkedInToolkit()
+ reddit_toolkit = RedditToolkit()
+ notion_toolkit = NotionToolkit()
+ slack_toolkit = SlackToolkit()
+ search_toolkit = SearchToolkit()
+ terminal_toolkit = TerminalToolkit()
+ note_toolkit = NoteTakingToolkit(working_directory=WORKING_DIRECTORY)
+
+ # Add messaging to toolkits
+ whatsapp_toolkit = message_integration.register(whatsapp_toolkit)
+ twitter_toolkit = message_integration.register(twitter_toolkit)
+ linkedin_toolkit = message_integration.register(linkedin_toolkit)
+ reddit_toolkit = message_integration.register(reddit_toolkit)
+ notion_toolkit = message_integration.register(notion_toolkit)
+ slack_toolkit = message_integration.register(slack_toolkit)
+ search_toolkit = message_integration.register(search_toolkit)
+ terminal_toolkit = message_integration.register(terminal_toolkit)
+ note_toolkit = message_integration.register(note_toolkit)
+
+ return ChatAgent(
+ BaseMessage.make_assistant_message(
+ role_name="Social Medium Agent",
+ content=f"""
+You are a Social Media Management Assistant with comprehensive capabilities
+across multiple platforms. You MUST use the `send_message_to_user` tool to
+inform the user of every decision and action you take. Your message must
+include a short title and a one-sentence description. This is a mandatory
+part of your workflow. When you complete your task, your final response must
+be a comprehensive summary of your actions, presented in a clear, detailed,
+and easy-to-read format. Avoid using markdown tables for presenting data;
+use plain text formatting instead.
+
+You are now working in `{WORKING_DIRECTORY}`. All your work
+related to local operations should be done in that directory.
+
+Your integrated toolkits enable you to:
+
+1. WhatsApp Business Management (WhatsAppToolkit):
+ - Send text and template messages to customers via the WhatsApp Business
+ API.
+ - Retrieve business profile information.
+
+2. Twitter Account Management (TwitterToolkit):
+ - Create tweets with text content, polls, or as quote tweets.
+ - Delete existing tweets.
+ - Retrieve user profile information.
+
+3. LinkedIn Professional Networking (LinkedInToolkit):
+ - Create posts on LinkedIn.
+ - Delete existing posts.
+ - Retrieve authenticated user's profile information.
+
+4. Reddit Content Analysis (RedditToolkit):
+ - Collect top posts and comments from specified subreddits.
+ - Perform sentiment analysis on Reddit comments.
+ - Track keyword discussions across multiple subreddits.
+
+5. Notion Workspace Management (NotionToolkit):
+ - List all pages and users in a Notion workspace.
+ - Retrieve and extract text content from Notion blocks.
+
+6. Slack Workspace Interaction (SlackToolkit):
+ - Create new Slack channels (public or private).
+ - Join or leave existing channels.
+ - Send and delete messages in channels.
+ - Retrieve channel information and message history.
+
+7. Human Interaction (HumanToolkit):
+ - Ask questions to users and send messages via console.
+
+8. Agent Communication:
+ - Communicate with other agents using messaging tools when collaboration
+ is needed. Use `list_available_agents` to see available team members and
+ `send_message` to coordinate with them, especially when you need content
+ from document agents or research from search agents.
+
+9. File System Access:
+ - You can use terminal tools to interact with the local file system in
+ your working directory (`{WORKING_DIRECTORY}`), for example, to access
+ files needed for posting. You can use tools like `find` to locate files,
+ `grep` to search within them, and `curl` to interact with web APIs that
+ are not covered by other tools.
+
+When assisting users, always:
+- Identify which platform's functionality is needed for the task.
+- Check if required API credentials are available before attempting
+operations.
+- Provide clear explanations of what actions you're taking.
+- Handle rate limits and API restrictions appropriately.
+- Ask clarifying questions when user requests are ambiguous.""",
+ ),
+ model=model,
+ tools=[
+ *whatsapp_toolkit.get_tools(),
+ *twitter_toolkit.get_tools(),
+ *linkedin_toolkit.get_tools(),
+ *reddit_toolkit.get_tools(),
+ *notion_toolkit.get_tools(),
+ *slack_toolkit.get_tools(),
+ send_message_to_user,
+ HumanToolkit().ask_human_via_console,
+ *search_toolkit.get_tools(),
+ *terminal_toolkit.get_tools(),
+ *note_toolkit.get_tools(),
+ ],
+ )
+
+
+async def main():
+ # Ensure working directory exists
+ os.makedirs(WORKING_DIRECTORY, exist_ok=True)
+
+ # google_drive_mcp_toolkit = GoogleDriveMCPToolkit(
+ # credentials_path="path/to/credentials.json"
+ # )
+
+ # Initialize the AgentCommunicationToolkit
+ msg_toolkit = AgentCommunicationToolkit(max_message_history=100)
+
+ # Initialize message integration for use in coordinator and task agents
+ message_integration = ToolkitMessageIntegration(
+ message_handler=send_message_to_user
+ )
+
+ # await google_drive_mcp_toolkit.connect()
+
+ # Create a single model backend for all agents
+ model_backend = ModelFactory.create(
+ model_platform=ModelPlatformType.OPENAI,
+ model_type=ModelType.GPT_4_1_MINI,
+ model_config_dict={
+ "stream": False,
+ },
+ )
+
+ model_backend_reason = ModelFactory.create(
+ model_platform=ModelPlatformType.OPENAI,
+ model_type=ModelType.GPT_4_1,
+ model_config_dict={
+ "stream": False,
+ },
+ )
+
+ task_id = 'workforce_task'
+
+ # Create custom agents for the workforce
+ coordinator_agent = ChatAgent(
+ system_message=(
+ f""""
+You are a helpful coordinator.
+- You are now working in system {platform.system()} with architecture
+{platform.machine()} at working directory `{WORKING_DIRECTORY}`. All your
+work related to local operations should be done in that directory.
+The current date is {datetime.date.today()}.
+
+- You MUST use the `send_message_to_user` tool to inform the user of every
+ decision and action you take. Your message must include a short title and
+ a one-sentence description. This is a mandatory part of your workflow.
+
+- If a task assigned to another agent fails, you should re-assign it to the
+`Developer_Agent`. The `Developer_Agent` is a powerful agent with terminal
+access and can resolve a wide range of issues.
+ """
+ ),
+ model=model_backend_reason,
+ tools=[
+ send_message_to_user,
+ *message_integration.register(
+ NoteTakingToolkit(working_directory=WORKING_DIRECTORY)
+ ).get_tools(),
+ ],
+ )
+ task_agent = ChatAgent(
+ f"""
+
+You are a helpful task planner.
+- You are now working in system {platform.system()} with architecture
+{platform.machine()} at working directory `{WORKING_DIRECTORY}`. All your
+work related to local operations should be done in that directory.
+The current date is {datetime.date.today()}.
+
+- You MUST use the `send_message_to_user` tool to inform the user of every
+ decision and action you take. Your message must include a short title and
+ a one-sentence description. This is a mandatory part of your workflow.
+ """,
+ model=model_backend_reason,
+ tools=[
+ send_message_to_user,
+ *message_integration.register(
+ NoteTakingToolkit(working_directory=WORKING_DIRECTORY)
+ ).get_tools(),
+ ],
+ )
+ new_worker_agent = ChatAgent(
+ f"You are a helpful worker. You MUST use the "
+ f"`send_message_to_user` tool to inform the user of every "
+ f"decision and action you take. Your message must include a short "
+ f"title and a one-sentence description. This is a mandatory part "
+ f"of your workflow. When you complete your task, your final response "
+ f"must be a comprehensive summary of your work, presented in a clear, "
+ f"detailed, and easy-to-read format. Avoid using markdown tables for "
+ f"presenting data; use plain text formatting instead. You are now "
+ f"working in "
+ f"`{WORKING_DIRECTORY}` All your work related to local "
+ "operations should be done in that "
+ "directory. You can also communicate with other agents "
+ "using messaging tools - use `list_available_agents` to see "
+ "available team members and `send_message` to coordinate work "
+ "and ask for help when needed. "
+ "### Note-Taking: You have access to comprehensive note-taking tools "
+ "for documenting work progress and collaborating with team members. "
+ "Use create_note, append_note, read_note, and list_note to track "
+ "your work, share findings, and access information from other agents. "
+ "Create notes for work progress, discoveries, and collaboration "
+ "points.",
+ model=model_backend,
+ tools=[
+ send_message_to_user,
+ HumanToolkit().ask_human_via_console,
+ *message_integration.register(
+ NoteTakingToolkit(working_directory=WORKING_DIRECTORY)
+ ).get_tools(),
+ ],
+ )
+
+ # Create agents using factory functions
+ search_agent = search_agent_factory(model_backend, task_id)
+ developer_agent = developer_agent_factory(
+ model_backend_reason,
+ task_id,
+ )
+ document_agent = document_agent_factory(
+ model_backend_reason,
+ task_id,
+ # google_drive_mcp_toolkit
+ )
+ multi_modal_agent = multi_modal_agent_factory(model_backend, task_id)
+ # social_medium_agent = social_medium_agent_factory(
+ # model_backend, task_id
+ # )
+
+ # Register all agents with the communication toolkit
+ # msg_toolkit.register_agent("Coordinator", coordinator_agent)
+ # msg_toolkit.register_agent("Task_Planner", task_agent)
+ msg_toolkit.register_agent("Worker", new_worker_agent)
+ msg_toolkit.register_agent("Search_Agent", search_agent)
+ msg_toolkit.register_agent("Developer_Agent", developer_agent)
+ msg_toolkit.register_agent("Document_Agent", document_agent)
+ msg_toolkit.register_agent("Multi_Modal_Agent", multi_modal_agent)
+ # msg_toolkit.register_agent("Social_Medium_Agent",
+ # social_medium_agent)
+
+ # # Add communication tools to all agents
+ # communication_tools = msg_toolkit.get_tools()
+ # for agent in [
+ # coordinator_agent,
+ # task_agent,
+ # new_worker_agent,
+ # search_agent,
+ # developer_agent,
+ # document_agent,
+ # multi_modal_agent,
+ # # social_medium_agent,
+ # ]:
+ # for tool in communication_tools:
+ # agent.add_tool(tool)
+
+ # Create workforce instance before adding workers
+ workforce = Workforce(
+ 'A workforce',
+ graceful_shutdown_timeout=30.0, # 30 seconds for debugging
+ share_memory=False,
+ coordinator_agent=coordinator_agent,
+ task_agent=task_agent,
+ new_worker_agent=new_worker_agent,
+ use_structured_output_handler=False,
+ )
+
+ workforce.add_single_agent_worker(
+ "Search Agent: Can search the web, extract webpage content, "
+ "simulate browser actions, and provide relevant information to "
+ "solve the given task.",
+ worker=search_agent,
+ ).add_single_agent_worker(
+ "Developer Agent: A skilled coding assistant that can write and "
+ "execute code, run terminal commands, control the desktop using "
+ "pyautogui, and verify solutions to complete tasks.",
+ worker=developer_agent,
+ ).add_single_agent_worker(
+ "Document Agent: A document processing assistant for creating, "
+ "modifying, and managing various document formats, including "
+ "presentations.",
+ worker=document_agent,
+ ).add_single_agent_worker(
+ "Multi-Modal Agent: A multi-modal processing assistant for "
+ "analyzing, and generating media content like audio and images.",
+ worker=multi_modal_agent,
+ )
+
+ # specify the task to be solved
+ human_task = Task(
+ content=(
+ """
+Analyze the UK healthcare industry to support the planning of my next company.
+Provide a comprehensive market overview, including current trends, growth
+projections, and relevant regulations. Identify the top 5-10 major competitors
+in the space, including their names, website URLs, estimated market size or
+share, core services or products, key strengths, and notable weaknesses. Also
+highlight any significant opportunities, gaps, or underserved segments within
+the market. Present all findings in a well-structured, professional HTML
+report.
+ """
+ ),
+ id='0',
+ )
+
+ # Use the async version directly to avoid hanging with async tools
+ await workforce.process_task_async(human_task)
+
+ # Test WorkforceLogger features
+ print("\n--- Workforce Log Tree ---")
+ print(workforce.get_workforce_log_tree())
+
+ print("\n--- Workforce KPIs ---")
+ kpis = workforce.get_workforce_kpis()
+ for key, value in kpis.items():
+ print(f"{key}: {value}")
+
+ log_file_path = "eigent_logs.json"
+ print(f"\n--- Dumping Workforce Logs to {log_file_path} ---")
+ workforce.dump_workforce_logs(log_file_path)
+ print(f"Logs dumped. Please check the file: {log_file_path}")
+
+
+if __name__ == "__main__":
+ asyncio.run(main())
diff --git a/pyproject.toml b/pyproject.toml
index 6e5128b51..6e087e475 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "camel-ai"
-version = "0.2.73a2"
+version = "0.2.73a3"
description = "Communicative Agents for AI Society Study"
authors = [{ name = "CAMEL-AI.org" }]
requires-python = ">=3.10,<3.13"
diff --git a/test/toolkits/test_excel_toolkit.py b/test/toolkits/test_excel_toolkit.py
index 00c4f6b7b..fbe9521be 100644
--- a/test/toolkits/test_excel_toolkit.py
+++ b/test/toolkits/test_excel_toolkit.py
@@ -24,7 +24,9 @@ from camel.toolkits import ExcelToolkit
@pytest.fixture
def excel_toolkit():
- return ExcelToolkit()
+ with tempfile.TemporaryDirectory() as temp_dir:
+ toolkit = ExcelToolkit(working_directory=temp_dir)
+ yield toolkit
@pytest.fixture
@@ -211,12 +213,13 @@ def test_get_tools(excel_toolkit):
r"""Test the get_tools method returns the correct tools."""
tools = excel_toolkit.get_tools()
- assert len(tools) == 18
+ assert len(tools) == 19
# Check that all expected function names are present
expected_function_names = [
"extract_excel_content",
"create_workbook",
+ "save_workbook",
"delete_workbook",
"export_sheet_to_csv",
"create_sheet",
@@ -241,88 +244,57 @@ def test_get_tools(excel_toolkit):
def test_create_workbook(excel_toolkit):
r"""Test creating a new workbook."""
- with tempfile.NamedTemporaryFile(
- suffix=".xlsx", delete=False
- ) as temp_file:
- temp_path = temp_file.name
+ data = [['Name', 'Age'], ['Alice', 25], ['Bob', 30]]
+ result = excel_toolkit.create_workbook('test.xlsx', 'TestSheet', data)
- try:
- data = [['Name', 'Age'], ['Alice', 25], ['Bob', 30]]
- result = excel_toolkit.create_workbook(temp_path, 'TestSheet', data)
+ assert "Workbook created successfully" in result
+ assert excel_toolkit.wb is not None
+ assert 'TestSheet' in excel_toolkit.wb.sheetnames
- assert "Workbook created successfully" in result
- assert excel_toolkit.wb is not None
- assert excel_toolkit.file_path == temp_path
- assert 'TestSheet' in excel_toolkit.wb.sheetnames
- finally:
- if os.path.exists(temp_path):
- os.remove(temp_path)
+ # Verify file was created
+ file_path = os.path.join(excel_toolkit.working_directory, 'test.xlsx')
+ assert os.path.exists(file_path)
def test_create_workbook_without_data(excel_toolkit):
r"""Test creating a workbook without data."""
- with tempfile.NamedTemporaryFile(
- suffix=".xlsx", delete=False
- ) as temp_file:
- temp_path = temp_file.name
-
- try:
- result = excel_toolkit.create_workbook(temp_path)
+ result = excel_toolkit.create_workbook('test_no_data.xlsx')
- assert "Workbook created successfully" in result
- assert excel_toolkit.wb is not None
- assert excel_toolkit.file_path == temp_path
- finally:
- if os.path.exists(temp_path):
- os.remove(temp_path)
+ assert "Workbook created successfully" in result
+ assert excel_toolkit.wb is not None
def test_delete_workbook(excel_toolkit):
r"""Test deleting a workbook."""
- with tempfile.NamedTemporaryFile(
- suffix=".xlsx", delete=False
- ) as temp_file:
- temp_path = temp_file.name
+ # Create a file first
+ excel_toolkit.create_workbook('test_delete.xlsx')
+ file_path = os.path.join(
+ excel_toolkit.working_directory, 'test_delete.xlsx'
+ )
+ assert os.path.exists(file_path)
- try:
- # Create a file first
- excel_toolkit.create_workbook(temp_path)
- assert os.path.exists(temp_path)
-
- # Delete the workbook
- result = excel_toolkit.delete_workbook(temp_path)
- assert "deleted successfully" in result
- assert not os.path.exists(temp_path)
- finally:
- if os.path.exists(temp_path):
- os.remove(temp_path)
+ # Delete the workbook
+ result = excel_toolkit.delete_workbook('test_delete.xlsx')
+ assert "deleted successfully" in result
+ assert not os.path.exists(file_path)
def test_delete_workbook_nonexistent(excel_toolkit):
r"""Test deleting a non-existent workbook."""
result = excel_toolkit.delete_workbook("nonexistent.xlsx")
- assert "does not exist" in result
+ assert "Error: File nonexistent.xlsx does not exist" in result
def test_create_sheet(excel_toolkit):
r"""Test creating a new sheet."""
- with tempfile.NamedTemporaryFile(
- suffix=".xlsx", delete=False
- ) as temp_file:
- temp_path = temp_file.name
-
- try:
- # Create workbook first
- excel_toolkit.create_workbook(temp_path)
+ # Create workbook first
+ excel_toolkit.create_workbook('test_sheets.xlsx')
- data = [['Name', 'Age'], ['Alice', 25]]
- result = excel_toolkit.create_sheet('NewSheet', data)
+ data = [['Name', 'Age'], ['Alice', 25]]
+ result = excel_toolkit.create_sheet('NewSheet', data)
- assert "created successfully" in result
- assert 'NewSheet' in excel_toolkit.wb.sheetnames
- finally:
- if os.path.exists(temp_path):
- os.remove(temp_path)
+ assert "created successfully" in result
+ assert 'NewSheet' in excel_toolkit.wb.sheetnames
def test_create_sheet_no_workbook(excel_toolkit):
@@ -333,115 +305,70 @@ def test_create_sheet_no_workbook(excel_toolkit):
def test_delete_sheet(excel_toolkit):
r"""Test deleting a sheet."""
- with tempfile.NamedTemporaryFile(
- suffix=".xlsx", delete=False
- ) as temp_file:
- temp_path = temp_file.name
+ # Create workbook with multiple sheets
+ excel_toolkit.create_workbook('test_delete_sheet.xlsx')
+ excel_toolkit.create_sheet('SheetToDelete')
- try:
- # Create workbook with multiple sheets
- excel_toolkit.create_workbook(temp_path)
- excel_toolkit.create_sheet('SheetToDelete')
-
- assert 'SheetToDelete' in excel_toolkit.wb.sheetnames
+ assert 'SheetToDelete' in excel_toolkit.wb.sheetnames
- result = excel_toolkit.delete_sheet('SheetToDelete')
- assert "deleted successfully" in result
- assert 'SheetToDelete' not in excel_toolkit.wb.sheetnames
- finally:
- if os.path.exists(temp_path):
- os.remove(temp_path)
+ result = excel_toolkit.delete_sheet('SheetToDelete')
+ assert "deleted successfully" in result
+ assert 'SheetToDelete' not in excel_toolkit.wb.sheetnames
def test_delete_sheet_nonexistent(excel_toolkit):
r"""Test deleting a non-existent sheet."""
- with tempfile.NamedTemporaryFile(
- suffix=".xlsx", delete=False
- ) as temp_file:
- temp_path = temp_file.name
-
- try:
- excel_toolkit.create_workbook(temp_path)
- result = excel_toolkit.delete_sheet('NonexistentSheet')
- assert "does not exist" in result
- finally:
- if os.path.exists(temp_path):
- os.remove(temp_path)
+ excel_toolkit.create_workbook('test_delete_nonexist.xlsx')
+ result = excel_toolkit.delete_sheet('NonexistentSheet')
+ assert "does not exist" in result
def test_clear_sheet(excel_toolkit):
r"""Test clearing a sheet."""
- with tempfile.NamedTemporaryFile(
- suffix=".xlsx", delete=False
- ) as temp_file:
- temp_path = temp_file.name
-
- try:
- # Create workbook with data
- data = [['Name', 'Age'], ['Alice', 25], ['Bob', 30]]
- excel_toolkit.create_workbook(temp_path, 'TestSheet', data)
+ # Create workbook with data
+ data = [['Name', 'Age'], ['Alice', 25], ['Bob', 30]]
+ excel_toolkit.create_workbook('test_clear.xlsx', 'TestSheet', data)
- # Clear the sheet
- result = excel_toolkit.clear_sheet('TestSheet')
- assert "cleared successfully" in result
+ # Clear the sheet
+ result = excel_toolkit.clear_sheet('TestSheet')
+ assert "cleared successfully" in result
- # Verify sheet is empty
- rows = excel_toolkit.get_rows('TestSheet')
- assert len(rows) == 0
- finally:
- if os.path.exists(temp_path):
- os.remove(temp_path)
+ # Verify sheet is empty
+ rows = excel_toolkit.get_rows('TestSheet')
+ assert len(rows) == 0
def test_add_data_to_sheet(excel_toolkit):
r"""Test adding data to a sheet using append_row."""
- with tempfile.NamedTemporaryFile(
- suffix=".xlsx", delete=False
- ) as temp_file:
- temp_path = temp_file.name
+ excel_toolkit.create_workbook('test_add_data.xlsx', 'TestSheet')
- try:
- excel_toolkit.create_workbook(temp_path, 'TestSheet')
-
- # Add data using append_row
- result1 = excel_toolkit.append_row('TestSheet', ['Alice', 25])
- result2 = excel_toolkit.append_row('TestSheet', ['Bob', 30])
- assert "appended to sheet" in result1
- assert "appended to sheet" in result2
-
- # Verify data was added
- rows = excel_toolkit.get_rows('TestSheet')
- assert len(rows) == 2
- assert rows[0] == ['Alice', 25]
- assert rows[1] == ['Bob', 30]
- finally:
- if os.path.exists(temp_path):
- os.remove(temp_path)
+ # Add data using append_row
+ result1 = excel_toolkit.append_row('TestSheet', ['Alice', 25])
+ result2 = excel_toolkit.append_row('TestSheet', ['Bob', 30])
+ assert "appended to sheet" in result1
+ assert "appended to sheet" in result2
+
+ # Verify data was added
+ rows = excel_toolkit.get_rows('TestSheet')
+ assert len(rows) == 2
+ assert rows[0] == ['Alice', 25]
+ assert rows[1] == ['Bob', 30]
def test_get_rows(excel_toolkit):
r"""Test getting rows from a sheet."""
- with tempfile.NamedTemporaryFile(
- suffix=".xlsx", delete=False
- ) as temp_file:
- temp_path = temp_file.name
+ data = [['Name', 'Age'], ['Alice', 25], ['Bob', 30], ['Charlie', 35]]
+ excel_toolkit.create_workbook('test_get_rows.xlsx', 'TestSheet', data)
- try:
- data = [['Name', 'Age'], ['Alice', 25], ['Bob', 30], ['Charlie', 35]]
- excel_toolkit.create_workbook(temp_path, 'TestSheet', data)
-
- # Get all rows
- all_rows = excel_toolkit.get_rows('TestSheet')
- assert len(all_rows) == 4
-
- # Get specific range
- range_rows = excel_toolkit.get_rows('TestSheet', 2, 3)
- assert len(range_rows) == 2
- assert range_rows[0] == ['Alice', 25]
- assert range_rows[1] == ['Bob', 30]
- finally:
- if os.path.exists(temp_path):
- os.remove(temp_path)
+ # Get all rows
+ all_rows = excel_toolkit.get_rows('TestSheet')
+ assert len(all_rows) == 4
+
+ # Get specific range
+ range_rows = excel_toolkit.get_rows('TestSheet', 2, 3)
+ assert len(range_rows) == 2
+ assert range_rows[0] == ['Alice', 25]
+ assert range_rows[1] == ['Bob', 30]
def test_get_rows_no_workbook(excel_toolkit):
@@ -452,368 +379,267 @@ def test_get_rows_no_workbook(excel_toolkit):
def test_update_row(excel_toolkit):
r"""Test updating a row."""
- with tempfile.NamedTemporaryFile(
- suffix=".xlsx", delete=False
- ) as temp_file:
- temp_path = temp_file.name
+ data = [['Name', 'Age'], ['Alice', 25], ['Bob', 30]]
+ excel_toolkit.create_workbook('test_update_row.xlsx', 'TestSheet', data)
- try:
- data = [['Name', 'Age'], ['Alice', 25], ['Bob', 30]]
- excel_toolkit.create_workbook(temp_path, 'TestSheet', data)
+ new_data = ['Alice Updated', 26]
+ result = excel_toolkit.update_row('TestSheet', 2, new_data)
+ assert "Row 2 updated in sheet TestSheet successfully" in result
- new_data = ['Alice Updated', 26]
- result = excel_toolkit.update_row('TestSheet', 2, new_data)
- assert "Row 2 updated in sheet TestSheet successfully" in result
-
- # Verify row was updated
- rows = excel_toolkit.get_rows('TestSheet')
- assert rows[1] == ['Alice Updated', 26]
- finally:
- if os.path.exists(temp_path):
- os.remove(temp_path)
+ # Verify row was updated
+ rows = excel_toolkit.get_rows('TestSheet')
+ assert rows[1] == ['Alice Updated', 26]
def test_append_or_update_row_new(excel_toolkit):
r"""Test appending a new row using append_row."""
- with tempfile.NamedTemporaryFile(
- suffix=".xlsx", delete=False
- ) as temp_file:
- temp_path = temp_file.name
+ data = [['Name', 'Age'], ['Alice', 25]]
+ excel_toolkit.create_workbook('test_append_new.xlsx', 'TestSheet', data)
- try:
- data = [['Name', 'Age'], ['Alice', 25]]
- excel_toolkit.create_workbook(temp_path, 'TestSheet', data)
+ new_data = ['Bob', 30]
+ result = excel_toolkit.append_row('TestSheet', new_data)
+ assert "appended to sheet" in result
- new_data = ['Bob', 30]
- result = excel_toolkit.append_row('TestSheet', new_data)
- assert "appended to sheet" in result
-
- # Verify new row was added
- rows = excel_toolkit.get_rows('TestSheet')
- assert len(rows) == 3
- assert rows[2] == ['Bob', 30]
- finally:
- if os.path.exists(temp_path):
- os.remove(temp_path)
+ # Verify new row was added
+ rows = excel_toolkit.get_rows('TestSheet')
+ assert len(rows) == 3
+ assert rows[2] == ['Bob', 30]
def test_append_or_update_row_existing(excel_toolkit):
r"""Test updating an existing row using update_row."""
- with tempfile.NamedTemporaryFile(
- suffix=".xlsx", delete=False
- ) as temp_file:
- temp_path = temp_file.name
+ data = [['Name', 'Age'], ['Alice', 25], ['Bob', 30]]
+ excel_toolkit.create_workbook(
+ 'test_update_existing.xlsx', 'TestSheet', data
+ )
- try:
- data = [['Name', 'Age'], ['Alice', 25], ['Bob', 30]]
- excel_toolkit.create_workbook(temp_path, 'TestSheet', data)
+ updated_data = ['Alice', 26] # Same name, different age
+ result = excel_toolkit.update_row('TestSheet', 2, updated_data)
+ assert "updated in sheet TestSheet successfully" in result
- updated_data = ['Alice', 26] # Same name, different age
- result = excel_toolkit.update_row('TestSheet', 2, updated_data)
- assert "updated in sheet TestSheet successfully" in result
-
- # Verify row was updated
- rows = excel_toolkit.get_rows('TestSheet')
- assert rows[1] == ['Alice', 26]
- finally:
- if os.path.exists(temp_path):
- os.remove(temp_path)
+ # Verify row was updated
+ rows = excel_toolkit.get_rows('TestSheet')
+ assert rows[1] == ['Alice', 26]
def test_delete_rows(excel_toolkit):
r"""Test deleting rows."""
- with tempfile.NamedTemporaryFile(
- suffix=".xlsx", delete=False
- ) as temp_file:
- temp_path = temp_file.name
-
- try:
- data = [['Name', 'Age'], ['Alice', 25], ['Bob', 30], ['Charlie', 35]]
- excel_toolkit.create_workbook(temp_path, 'TestSheet', data)
+ data = [['Name', 'Age'], ['Alice', 25], ['Bob', 30], ['Charlie', 35]]
+ excel_toolkit.create_workbook('test_delete_rows.xlsx', 'TestSheet', data)
- # Delete single row
- result = excel_toolkit.delete_rows('TestSheet', 2)
- assert (
- "Deleted rows 2 to 2 from sheet TestSheet successfully" in result
- )
+ # Delete single row
+ result = excel_toolkit.delete_rows('TestSheet', 2)
+ assert "Deleted rows 2 to 2 from sheet TestSheet successfully" in result
- # Verify row was deleted
- rows = excel_toolkit.get_rows('TestSheet')
- assert len(rows) == 3
- assert rows[0] == ['Name', 'Age']
- assert rows[1] == ['Bob', 30]
- finally:
- if os.path.exists(temp_path):
- os.remove(temp_path)
+ # Verify row was deleted
+ rows = excel_toolkit.get_rows('TestSheet')
+ assert len(rows) == 3
+ assert rows[0] == ['Name', 'Age']
+ assert rows[1] == ['Bob', 30]
def test_delete_columns(excel_toolkit):
r"""Test deleting columns."""
- with tempfile.NamedTemporaryFile(
- suffix=".xlsx", delete=False
- ) as temp_file:
- temp_path = temp_file.name
+ data = [
+ ['Name', 'Age', 'City'],
+ ['Alice', 25, 'NY'],
+ ['Bob', 30, 'SF'],
+ ]
+ excel_toolkit.create_workbook('test_delete_cols.xlsx', 'TestSheet', data)
- try:
- data = [
- ['Name', 'Age', 'City'],
- ['Alice', 25, 'NY'],
- ['Bob', 30, 'SF'],
- ]
- excel_toolkit.create_workbook(temp_path, 'TestSheet', data)
-
- # Delete second column (Age)
- result = excel_toolkit.delete_columns('TestSheet', 2)
- assert (
- "Deleted columns 2 to 2 from sheet TestSheet successfully"
- in result
- )
+ # Delete second column (Age)
+ result = excel_toolkit.delete_columns('TestSheet', 2)
+ assert "Deleted columns 2 to 2 from sheet TestSheet successfully" in result
- # Verify column was deleted
- rows = excel_toolkit.get_rows('TestSheet')
- assert len(rows) == 3
- assert rows[0] == ['Name', 'City']
- assert rows[1] == ['Alice', 'NY']
- finally:
- if os.path.exists(temp_path):
- os.remove(temp_path)
+ # Verify column was deleted
+ rows = excel_toolkit.get_rows('TestSheet')
+ assert len(rows) == 3
+ assert rows[0] == ['Name', 'City']
+ assert rows[1] == ['Alice', 'NY']
def test_get_cell_value(excel_toolkit):
r"""Test getting cell value."""
- with tempfile.NamedTemporaryFile(
- suffix=".xlsx", delete=False
- ) as temp_file:
- temp_path = temp_file.name
+ data = [['Name', 'Age'], ['Alice', 25]]
+ excel_toolkit.create_workbook('test_get_cell.xlsx', 'TestSheet', data)
- try:
- data = [['Name', 'Age'], ['Alice', 25]]
- excel_toolkit.create_workbook(temp_path, 'TestSheet', data)
+ value = excel_toolkit.get_cell_value('TestSheet', 'A1')
+ assert value == 'Name'
- value = excel_toolkit.get_cell_value('TestSheet', 'A1')
- assert value == 'Name'
-
- value = excel_toolkit.get_cell_value('TestSheet', 'B2')
- assert value == 25
- finally:
- if os.path.exists(temp_path):
- os.remove(temp_path)
+ value = excel_toolkit.get_cell_value('TestSheet', 'B2')
+ assert value == 25
def test_set_cell_value(excel_toolkit):
r"""Test setting cell value."""
- with tempfile.NamedTemporaryFile(
- suffix=".xlsx", delete=False
- ) as temp_file:
- temp_path = temp_file.name
+ data = [['Name', 'Age'], ['Alice', 25]]
+ excel_toolkit.create_workbook('test_set_cell.xlsx', 'TestSheet', data)
- try:
- data = [['Name', 'Age'], ['Alice', 25]]
- excel_toolkit.create_workbook(temp_path, 'TestSheet', data)
+ result = excel_toolkit.set_cell_value('TestSheet', 'A1', 'Updated Name')
+ assert "updated successfully" in result
- result = excel_toolkit.set_cell_value(
- 'TestSheet', 'A1', 'Updated Name'
- )
- assert "updated successfully" in result
-
- # Verify cell was updated
- value = excel_toolkit.get_cell_value('TestSheet', 'A1')
- assert value == 'Updated Name'
- finally:
- if os.path.exists(temp_path):
- os.remove(temp_path)
+ # Verify cell was updated
+ value = excel_toolkit.get_cell_value('TestSheet', 'A1')
+ assert value == 'Updated Name'
def test_get_column_data(excel_toolkit):
r"""Test getting column data."""
- with tempfile.NamedTemporaryFile(
- suffix=".xlsx", delete=False
- ) as temp_file:
- temp_path = temp_file.name
+ data = [['Name', 'Age'], ['Alice', 25], ['Bob', 30]]
+ excel_toolkit.create_workbook('test_get_col.xlsx', 'TestSheet', data)
- try:
- data = [['Name', 'Age'], ['Alice', 25], ['Bob', 30]]
- excel_toolkit.create_workbook(temp_path, 'TestSheet', data)
+ # Get column by number
+ col_data = excel_toolkit.get_column_data('TestSheet', 1)
+ assert col_data == ['Name', 'Alice', 'Bob']
- # Get column by number
- col_data = excel_toolkit.get_column_data('TestSheet', 1)
- assert col_data == ['Name', 'Alice', 'Bob']
-
- # Get column by letter
- col_data = excel_toolkit.get_column_data('TestSheet', 'B')
- assert col_data == ['Age', 25, 30]
- finally:
- if os.path.exists(temp_path):
- os.remove(temp_path)
+ # Get column by letter
+ col_data = excel_toolkit.get_column_data('TestSheet', 'B')
+ assert col_data == ['Age', 25, 30]
def test_find_cells(excel_toolkit):
r"""Test finding cells with specific value."""
- with tempfile.NamedTemporaryFile(
- suffix=".xlsx", delete=False
- ) as temp_file:
- temp_path = temp_file.name
+ data = [['Name', 'Age'], ['Alice', 25], ['Bob', 30], ['Alice', 35]]
+ excel_toolkit.create_workbook('test_find_cells.xlsx', 'TestSheet', data)
- try:
- data = [['Name', 'Age'], ['Alice', 25], ['Bob', 30], ['Alice', 35]]
- excel_toolkit.create_workbook(temp_path, 'TestSheet', data)
-
- # Find all cells with 'Alice'
- cells = excel_toolkit.find_cells('TestSheet', 'Alice')
- assert len(cells) == 2
- assert 'A2' in cells
- assert 'A4' in cells
-
- # Find in specific column
- cells = excel_toolkit.find_cells('TestSheet', 25, 2)
- assert len(cells) == 1
- assert 'B2' in cells
- finally:
- if os.path.exists(temp_path):
- os.remove(temp_path)
+ # Find all cells with 'Alice'
+ cells = excel_toolkit.find_cells('TestSheet', 'Alice')
+ assert len(cells) == 2
+ assert 'A2' in cells
+ assert 'A4' in cells
+
+ # Find in specific column
+ cells = excel_toolkit.find_cells('TestSheet', 25, 2)
+ assert len(cells) == 1
+ assert 'B2' in cells
def test_get_range_values(excel_toolkit):
r"""Test getting range values."""
- with tempfile.NamedTemporaryFile(
- suffix=".xlsx", delete=False
- ) as temp_file:
- temp_path = temp_file.name
+ data = [
+ ['Name', 'Age', 'City'],
+ ['Alice', 25, 'NY'],
+ ['Bob', 30, 'SF'],
+ ]
+ excel_toolkit.create_workbook('test_get_range.xlsx', 'TestSheet', data)
- try:
- data = [
- ['Name', 'Age', 'City'],
- ['Alice', 25, 'NY'],
- ['Bob', 30, 'SF'],
- ]
- excel_toolkit.create_workbook(temp_path, 'TestSheet', data)
-
- range_values = excel_toolkit.get_range_values('TestSheet', 'A1:C2')
- assert len(range_values) == 2
- assert range_values[0] == ['Name', 'Age', 'City']
- assert range_values[1] == ['Alice', 25, 'NY']
- finally:
- if os.path.exists(temp_path):
- os.remove(temp_path)
+ range_values = excel_toolkit.get_range_values('TestSheet', 'A1:C2')
+ assert len(range_values) == 2
+ assert range_values[0] == ['Name', 'Age', 'City']
+ assert range_values[1] == ['Alice', 25, 'NY']
def test_set_range_values(excel_toolkit):
r"""Test setting range values."""
- with tempfile.NamedTemporaryFile(
- suffix=".xlsx", delete=False
- ) as temp_file:
- temp_path = temp_file.name
-
- try:
- data = [['Name', 'Age'], ['Alice', 25]]
- excel_toolkit.create_workbook(temp_path, 'TestSheet', data)
+ data = [['Name', 'Age'], ['Alice', 25]]
+ excel_toolkit.create_workbook('test_set_range.xlsx', 'TestSheet', data)
- new_values = [['Bob', 30], ['Charlie', 35]]
- result = excel_toolkit.set_range_values(
- 'TestSheet', 'A2:B3', new_values
- )
- assert "Values set for range" in result
+ new_values = [['Bob', 30], ['Charlie', 35]]
+ result = excel_toolkit.set_range_values('TestSheet', 'A2:B3', new_values)
+ assert "Values set for range" in result
- # Verify values were set
- range_values = excel_toolkit.get_range_values('TestSheet', 'A2:B3')
- assert range_values == new_values
- finally:
- if os.path.exists(temp_path):
- os.remove(temp_path)
+ # Verify values were set
+ range_values = excel_toolkit.get_range_values('TestSheet', 'A2:B3')
+ assert range_values == new_values
def test_export_sheet_to_csv(excel_toolkit):
r"""Test exporting sheet to CSV."""
- with tempfile.NamedTemporaryFile(
- suffix=".xlsx", delete=False
- ) as temp_file:
- temp_path = temp_file.name
+ data = [['Name', 'Age'], ['Alice', 25], ['Bob', 30]]
+ excel_toolkit.create_workbook('test_export.xlsx', 'TestSheet', data)
- with tempfile.NamedTemporaryFile(suffix=".csv", delete=False) as csv_file:
- csv_path = csv_file.name
+ result = excel_toolkit.export_sheet_to_csv('TestSheet', 'exported.csv')
+ assert "exported to exported.csv" in result
- try:
- data = [['Name', 'Age'], ['Alice', 25], ['Bob', 30]]
- excel_toolkit.create_workbook(temp_path, 'TestSheet', data)
+ csv_path = os.path.join(excel_toolkit.working_directory, 'exported.csv')
+ assert os.path.exists(csv_path)
- result = excel_toolkit.export_sheet_to_csv('TestSheet', csv_path)
- assert "exported to CSV" in result
- assert os.path.exists(csv_path)
-
- # Verify CSV content
- df = pd.read_csv(csv_path)
- assert len(df) == 2
- assert list(df.columns) == ['Name', 'Age']
- finally:
- if os.path.exists(temp_path):
- os.remove(temp_path)
- if os.path.exists(csv_path):
- os.remove(csv_path)
+ # Verify CSV content
+ df = pd.read_csv(csv_path)
+ assert len(df) == 2
+ assert list(df.columns) == ['Name', 'Age']
def test_append_row(excel_toolkit):
r"""Test appending a row."""
- with tempfile.NamedTemporaryFile(
- suffix=".xlsx", delete=False
- ) as temp_file:
- temp_path = temp_file.name
+ data = [['Name', 'Age'], ['Alice', 25]]
+ excel_toolkit.create_workbook('test_append.xlsx', 'TestSheet', data)
- try:
- data = [['Name', 'Age'], ['Alice', 25]]
- excel_toolkit.create_workbook(temp_path, 'TestSheet', data)
+ new_row = ['Bob', 30]
+ result = excel_toolkit.append_row('TestSheet', new_row)
+ assert "appended to sheet" in result
- new_row = ['Bob', 30]
- result = excel_toolkit.append_row('TestSheet', new_row)
- assert "appended to sheet" in result
-
- # Verify row was appended
- rows = excel_toolkit.get_rows('TestSheet')
- assert len(rows) == 3
- assert rows[2] == ['Bob', 30]
- finally:
- if os.path.exists(temp_path):
- os.remove(temp_path)
+ # Verify row was appended
+ rows = excel_toolkit.get_rows('TestSheet')
+ assert len(rows) == 3
+ assert rows[2] == ['Bob', 30]
def test_save_workbook(excel_toolkit):
r"""Test saving workbook."""
- with tempfile.NamedTemporaryFile(
- suffix=".xlsx", delete=False
- ) as temp_file:
- temp_path = temp_file.name
+ excel_toolkit.create_workbook('test_save.xlsx')
- try:
- excel_toolkit.create_workbook(temp_path)
+ # Modify workbook
+ excel_toolkit.set_cell_value('Sheet1', 'A1', 'Test Value')
- # Modify workbook
- excel_toolkit.set_cell_value('Sheet1', 'A1', 'Test Value')
+ # Save workbook to a different file
+ result = excel_toolkit.save_workbook('test_saved.xlsx')
+ assert "Workbook saved successfully" in result
- # Save workbook
- result = excel_toolkit._save_workbook()
- assert "saved successfully" in result
-
- # Verify file exists and has content
- assert os.path.exists(temp_path)
- finally:
- if os.path.exists(temp_path):
- os.remove(temp_path)
+ # Verify file exists
+ file_path = os.path.join(
+ excel_toolkit.working_directory, 'test_saved.xlsx'
+ )
+ assert os.path.exists(file_path)
def test_save_workbook_no_workbook(excel_toolkit):
r"""Test saving when no workbook is loaded."""
- result = excel_toolkit._save_workbook()
- assert "No workbook loaded" in result
+ result = excel_toolkit.save_workbook('test.xlsx')
+ assert "No workbook is currently loaded" in result
+
+
+def test_create_workbook_no_filename(excel_toolkit):
+ r"""Test creating workbook without filename."""
+ result = excel_toolkit.create_workbook()
+ assert "Error: Filename is required" in result
+
+
+def test_create_workbook_invalid_extension(excel_toolkit):
+ r"""Test creating workbook with invalid extension."""
+ result = excel_toolkit.create_workbook('test.txt')
+ assert "Error: Filename must end with .xlsx extension" in result
+
+
+def test_create_workbook_existing_file(excel_toolkit):
+ r"""Test creating workbook when file already exists."""
+ # Create first file
+ excel_toolkit.create_workbook('duplicate.xlsx')
+
+ # Try to create same file again
+ result = excel_toolkit.create_workbook('duplicate.xlsx')
+ assert "Error: File duplicate.xlsx already exists" in result
+
+
+def test_export_sheet_to_csv_invalid_filename(excel_toolkit):
+ r"""Test exporting to CSV with invalid filename."""
+ excel_toolkit.create_workbook('test.xlsx', 'TestSheet')
+
+ # Test with no filename
+ result = excel_toolkit.export_sheet_to_csv('TestSheet', '')
+ assert "Error: CSV filename is required" in result
+ # Test with wrong extension
+ result = excel_toolkit.export_sheet_to_csv('TestSheet', 'test.txt')
+ assert "Error: CSV filename must end with .csv extension" in result
-def test_initialization_with_file_path(excel_toolkit, sample_xlsx_file):
- r"""Test initialization with existing file path."""
- toolkit = ExcelToolkit(file_path=sample_xlsx_file)
- assert toolkit.file_path == sample_xlsx_file
- assert toolkit.wb is not None
+def test_delete_workbook_invalid_filename(excel_toolkit):
+ r"""Test deleting workbook with invalid filename."""
+ # Test with no filename
+ result = excel_toolkit.delete_workbook('')
+ assert "Error: Filename is required" in result
-def test_initialization_with_nonexistent_file():
- r"""Test initialization with non-existent file path."""
- toolkit = ExcelToolkit(file_path="nonexistent.xlsx")
- assert toolkit.file_path == "nonexistent.xlsx"
- assert toolkit.wb is None
+ # Test with wrong extension
+ result = excel_toolkit.delete_workbook('test.txt')
+ assert "Error: Filename must end with .xlsx extension" in result
diff --git a/test/toolkits/test_message_integration.py b/test/toolkits/test_message_integration.py
index 4176944d2..4a3c3e970 100644
--- a/test/toolkits/test_message_integration.py
+++ b/test/toolkits/test_message_integration.py
@@ -72,9 +72,9 @@ class TestToolkitMessageIntegration(unittest.TestCase):
self.assertIn("Message successfully sent", result)
self.assertIn("Test Title", result)
- def test_add_messaging_to_toolkit_all_tools(self):
+ def test_register_all_tools(self):
r"""Test adding messaging to all tools in a toolkit."""
- enhanced_toolkit = self.message_integration.add_messaging_to_toolkit(
+ enhanced_toolkit = self.message_integration.register_toolkits(
self.toolkit
)
@@ -89,9 +89,9 @@ class TestToolkitMessageIntegration(unittest.TestCase):
self.assertIn('message_description', params)
self.assertIn('message_attachment', params)
- def test_add_messaging_to_toolkit_specific_tools(self):
+ def test_register_specific_tools(self):
r"""Test adding messaging to specific tools only."""
- enhanced_toolkit = self.message_integration.add_messaging_to_toolkit(
+ enhanced_toolkit = self.message_integration.register_toolkits(
self.toolkit, tool_names=['search_web']
)
@@ -122,7 +122,7 @@ class TestToolkitMessageIntegration(unittest.TestCase):
mock_send = Mock(return_value="Message sent")
self.message_integration.message_handler = mock_send
- enhanced_toolkit = self.message_integration.add_messaging_to_toolkit(
+ enhanced_toolkit = self.message_integration.register_toolkits(
self.toolkit
)
@@ -151,7 +151,7 @@ class TestToolkitMessageIntegration(unittest.TestCase):
mock_send = Mock(return_value="Message sent")
self.message_integration.message_handler = mock_send
- enhanced_toolkit = self.message_integration.add_messaging_to_toolkit(
+ enhanced_toolkit = self.message_integration.register_toolkits(
self.toolkit
)
@@ -167,7 +167,7 @@ class TestToolkitMessageIntegration(unittest.TestCase):
# Check original function still works
self.assertEqual(len(result), 2)
- def test_add_messaging_to_functions_with_callables(self):
+ def test_register_functions_with_callables(self):
r"""Test adding messaging to a list of callable functions."""
def process_text(text: str) -> str:
@@ -193,7 +193,7 @@ class TestToolkitMessageIntegration(unittest.TestCase):
"""
return a + b
- enhanced_tools = self.message_integration.add_messaging_to_functions(
+ enhanced_tools = self.message_integration.register_functions(
[process_text, calculate_sum], function_names=['process_text']
)
@@ -236,9 +236,7 @@ class TestToolkitMessageIntegration(unittest.TestCase):
),
)
- enhanced_toolkit = custom_integration.add_messaging_to_toolkit(
- self.toolkit
- )
+ enhanced_toolkit = custom_integration.register_toolkits(self.toolkit)
tools = enhanced_toolkit.get_tools()
search_tool = next(t for t in tools if t.func.__name__ == 'search_web')
@@ -275,7 +273,7 @@ class TestToolkitMessageIntegration(unittest.TestCase):
"""
return x + y
- enhanced_tools = self.message_integration.add_messaging_to_functions(
+ enhanced_tools = self.message_integration.register_functions(
[simple_func, func_with_args]
)
diff --git a/uv.lock b/uv.lock
index 5f95d07be..3ae86106b 100644
--- a/uv.lock
+++ b/uv.lock
@@ -647,7 +647,7 @@ wheels = [
[[package]]
name = "camel-ai"
-version = "0.2.73a2"
+version = "0.2.73a3"
source = { editable = "." }
dependencies = [
{ name = "colorama" },