🐫 CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org
Python agentai-societiesartificial-intelligencecommunicative-aicooperative-aideep-learninglarge-language-modelsmulti-agent-systemsnatural-language-processing
update tool decorator (#1691)
Asher-hssd64f52fdfe15
diff --git a/camel/toolkits/__init__.py b/camel/toolkits/__init__.pyindex 5a05e1c82..fa1bbe5d4 100644--- a/camel/toolkits/__init__.py+++ b/camel/toolkits/__init__.py@@ -17,6 +17,7 @@ from .function_tool import (get_openai_function_schema,get_openai_tool_schema,generate_docstring,+ tool,)from .open_api_specs.security_config import openapi_security_config@@ -106,6 +107,7 @@ __all__ = ['BaseToolkit','manual_timeout','FunctionTool',+ 'tool','get_openai_function_schema','get_openai_tool_schema',"generate_docstring",diff --git a/camel/toolkits/function_tool.py b/camel/toolkits/function_tool.pyindex b54ef852e..3142df1d4 100644--- a/camel/toolkits/function_tool.py+++ b/camel/toolkits/function_tool.py@@ -962,3 +962,89 @@ class FunctionTool:except SchemaError as e:raise eself.openai_tool_schema["function"]["parameters"]["properties"] = value+++def tool(+ func: Optional[Callable] = None,+ *,+ openai_tool_schema: Optional[Dict[str, Any]] = None,+ synthesize_schema: bool = False,+ synthesize_schema_model: Optional[BaseModelBackend] = None,+ synthesize_schema_max_retries: int = 2,+ synthesize_output: bool = False,+ synthesize_output_model: Optional[BaseModelBackend] = None,+ synthesize_output_format: Optional[Type[BaseModel]] = None,+):+ r"""A decorator that converts a Python function into a FunctionTool+ instance.++ This decorator can be used with or without parentheses:+ - @tool - without parentheses, uses default settings+ - @tool() - with parentheses, uses default settings+ - @tool(synthesize_output=True) - with custom settings++ Args:+ func (Optional[Callable], optional): The function to be decorated.+ This is automatically passed when using @tool without parentheses.+ (default: :obj:`None`)+ openai_tool_schema (Optional[Dict[str, Any]], optional): A+ user-defined OpenAI tool schema to override the default result.+ (default: :obj:`None`)+ synthesize_schema (bool, optional): Whether to enable schema synthesis.+ (default: :obj:`False`)+ synthesize_schema_model (Optional[BaseModelBackend], optional):+ Model to use for schema synthesis. (default: :obj:`None`)+ synthesize_schema_max_retries (int, optional): Maximum number of+ retries for schema synthesis. (default: :obj:`2`)+ synthesize_output (bool, optional): Whether to enable output synthesis.+ (default: :obj:`False`)+ synthesize_output_model (Optional[BaseModelBackend], optional):+ Model to use for output synthesis. (default: :obj:`None`)+ synthesize_output_format (Optional[Type[BaseModel]], optional):+ Format for synthesized output. (default: :obj:`None`)++ Returns:+ Callable[[Callable], FunctionTool]: A decorator function that converts+ the decorated function into a FunctionTool instance.++ Example:+ Using @tool without parentheses::++ @tool+ def add(a: int, b: int = 0) -> int:+ '''Add two numbers.'''+ return a + b++ Using @tool() with parentheses::++ @tool()+ def multiply(a: int, b: int) -> int:+ '''Multiply two numbers.'''+ return a * b+ """++ def decorator(f: Callable) -> FunctionTool:+ r"""The actual decorator function.++ Args:+ f (Callable): The function to be converted into a FunctionTool.++ Returns:+ FunctionTool: The function wrapped as a FunctionTool instance.+ """+ return FunctionTool(+ func=f,+ openai_tool_schema=openai_tool_schema,+ synthesize_schema=synthesize_schema,+ synthesize_schema_model=synthesize_schema_model,+ synthesize_schema_max_retries=synthesize_schema_max_retries,+ synthesize_output=synthesize_output,+ synthesize_output_model=synthesize_output_model,+ synthesize_output_format=synthesize_output_format,+ )++ # Support both @tool and @tool() usage patterns+ if func is not None:+ return decorator(func)+ else:+ return decoratordiff --git a/examples/toolkits/function_tool_example.py b/examples/toolkits/function_tool_example.pynew file mode 100644index 000000000..5a3c9260d--- /dev/null+++ b/examples/toolkits/function_tool_example.py@@ -0,0 +1,111 @@+# ========= Copyright 2023-2026 @ 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-2026 @ CAMEL-AI.org. All Rights Reserved. =========+from typing import Any, Dict++from camel.agents import ChatAgent+from camel.toolkits import tool+++@tool()+def calculate_bmi(+ weight: float,+ height: float,+) -> Dict[str, Any]:+ r"""Calculate BMI (Body Mass Index) and provide health status.++ Args:+ weight (float): Weight in kilograms.+ height (float): Height in meters.++ Returns:+ Dict[str, Any]: Dictionary containing BMI value and health status.+ """+ bmi = weight / (height * height)++ if bmi < 18.5:+ status = "Underweight"+ elif 18.5 <= bmi < 24.9:+ status = "Normal weight"+ elif 24.9 <= bmi < 29.9:+ status = "Overweight"+ else:+ status = "Obese"++ return {"bmi": round(bmi, 2), "status": status}+++def main():+ system_message = """You are a health assistant that helps calculate BMI.+ When users mention their height and weight, use the calculate_bmi tool to:+ 1. Calculate their BMI+ 2. Determine their health status+ 3. Provide the results in a clear format++ Do NOT perform the calculation yourself. Always use the tool."""++ agent = ChatAgent(+ system_message,+ tools=[calculate_bmi],+ )++ messages = [+ "I am 70 kg and 1.75 meters tall. What's my BMI?",+ "If someone is 80 kg and 1.8 meters, are they overweight?",+ "My friend weighs 65 kg with height 1.7 meters, check their BMI.",+ ]++ for msg in messages:+ print("\nUser:", msg)+ response = agent.step(msg)+ print("Assistant:", response.msgs[0].content)+ if "tool_calls" in response.info:+ print("\nTool Calls:")+ for call in response.info["tool_calls"]:+ print(call)+++if __name__ == "__main__":+ main()++'''+===============================================================================+User: I am 70 kg and 1.75 meters tall. What's my BMI?+Assistant: Your BMI is 22.86, which falls within the "Normal weight" category.++Tool Calls:+Tool Execution: calculate_bmi+ Args: {'weight': 70, 'height': 1.75}+ Result: {'bmi': 22.86, 'status': 'Normal weight'}+++User: If someone is 80 kg and 1.8 meters, are they overweight?+Assistant: For someone who is 80 kg and 1.8 meters tall, their BMI is 24.69,+ which is classified as "Normal weight." Therefore, they are not+ considered overweight.++Tool Calls:+Tool Execution: calculate_bmi+ Args: {'weight': 80, 'height': 1.8}+ Result: {'bmi': 24.69, 'status': 'Normal weight'}+++User: My friend weighs 65 kg with height 1.7 meters, check their BMI.+Assistant: Your friend's BMI is 22.49, which is categorized as "Normal weight."++Tool Calls:+Tool Execution: calculate_bmi+ Args: {'weight': 65, 'height': 1.7}+ Result: {'bmi': 22.49, 'status': 'Normal weight'}+===============================================================================+'''diff --git a/test/toolkits/test_function_tool_decorator.py b/test/toolkits/test_function_tool_decorator.pynew file mode 100644index 000000000..0065ad478--- /dev/null+++ b/test/toolkits/test_function_tool_decorator.py@@ -0,0 +1,143 @@+# ========= Copyright 2023-2026 @ 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-2026 @ CAMEL-AI.org. All Rights Reserved. =========+import pytest++from camel.toolkits import FunctionTool, tool+++@tool()+def add(+ a: int,+ b: int = 0,+) -> int:+ r"""Add two numbers and return their sum.++ Args:+ a (int): The first number to add.+ b (int, optional): The second number to add.+ (default: :obj:`0`)++ Returns:+ int: The sum of the two numbers.+ """+ return a + b+++@tool(synthesize_output=True)+def format_result(+ result: int,+) -> str:+ r"""Format the calculation result.++ Args:+ result (int): The number to format.++ Returns:+ str: A formatted string.+ """+ return f"Result: {result}"+++def test_basic_tool_decorator():+ r"""Test basic functionality of the tool decorator."""+ assert isinstance(add, FunctionTool)++ assert add(1, 2) == 3+ assert add(5) == 5+++def test_tool_schema_generation():+ r"""Test schema generation of the decorated function."""+ schema = add.get_openai_tool_schema()++ assert schema["type"] == "function"+ assert "function" in schema++ func_schema = schema["function"]+ assert func_schema["name"] == "add"+ assert "description" in func_schema+ assert "parameters" in func_schema++ params = func_schema["parameters"]+ assert "properties" in params+ assert "a" in params["properties"]+ assert "b" in params["properties"]+ assert params["properties"]["a"]["type"] == "integer"+ assert "description" in params["properties"]["a"]+++def test_tool_with_synthesis():+ r"""Test the tool decorator with output synthesis enabled."""+ assert format_result.synthesize_output is True++ result = format_result(42)+ assert isinstance(result, str)+ assert "42" in result+++def test_tool_without_parentheses():+ r"""Test the tool decorator without parentheses (@tool instead of+ @tool()).+ """++ @tool+ def subtract(a: int, b: int = 0) -> int:+ r"""Subtract two numbers.++ Args:+ a (int): The first number.+ b (int, optional): The number to subtract. (default: :obj:`0`)++ Returns:+ int: The difference.+ """+ return a - b++ assert isinstance(subtract, FunctionTool)+ assert subtract(5, 3) == 2+ assert subtract(10) == 10++ schema = subtract.get_openai_tool_schema()+ assert schema["function"]["name"] == "subtract"+++def test_custom_schema():+ r"""Test the tool decorator with custom schema."""+ custom_schema = {+ "type": "function",+ "function": {+ "name": "custom_add",+ "description": "Custom add function",+ "parameters": {+ "type": "object",+ "properties": {+ "a": {"type": "integer", "description": "First number"},+ "b": {"type": "integer", "description": "Second number"},+ },+ },+ },+ }++ @tool(openai_tool_schema=custom_schema)+ def custom_add(a: int, b: int = 0) -> int:+ r"""Custom add function."""+ return a + b++ schema = custom_add.get_openai_tool_schema()+ assert schema["function"]["name"] == "custom_add"+ assert schema["function"]["description"] == "Custom add function"+++if __name__ == "__main__":+ pytest.main([__file__])