Skip to content

armgit / camel

Public Imported from GitHub
0

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

feat: add think toolkit (#1958)

Rishabh53c312a4becf
diff --git a/camel/toolkits/__init__.py b/camel/toolkits/__init__.py
index 558b0827b..7da68879b 100644
--- a/camel/toolkits/__init__.py
+++ b/camel/toolkits/__init__.py
@@ -60,6 +60,7 @@ from .browser_toolkit import BrowserToolkit
from .file_write_toolkit import FileWriteToolkit
from .terminal_toolkit import TerminalToolkit
from .pubmed_toolkit import PubMedToolkit
+from .thinking_toolkit import ThinkingToolkit
__all__ = [
'BaseToolkit',
@@ -108,4 +109,5 @@ __all__ = [
'FileWriteToolkit',
'TerminalToolkit',
'PubMedToolkit',
+ 'ThinkingToolkit',
]
diff --git a/camel/toolkits/thinking_toolkit.py b/camel/toolkits/thinking_toolkit.py
new file mode 100644
index 000000000..071ebe30a
--- /dev/null
+++ b/camel/toolkits/thinking_toolkit.py
@@ -0,0 +1,74 @@
+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
+
+from typing import List, Optional
+
+from camel.logger import get_logger
+from camel.toolkits import FunctionTool
+from camel.toolkits.base import BaseToolkit
+
+logger = get_logger(__name__)
+
+
+class ThinkingToolkit(BaseToolkit):
+ r"""A toolkit for recording thoughts during reasoning processes.
+
+ Attributes:
+ thoughts (List[str]): A list to store the recorded thoughts.
+ """
+
+ def __init__(
+ self,
+ timeout: Optional[float] = None,
+ ):
+ r"""Initialize the ThinkingToolkit.
+
+ Args:
+ timeout (Optional[float]): The timeout for the toolkit.
+ (default: :obj: `None`)
+ """
+ super().__init__(timeout=timeout)
+ self.thoughts: List[str] = []
+
+ def think(self, thought: str) -> str:
+ r"""Use the tool to think about something.
+ It will not obtain new information or change the database, but just
+ append the thought to the log. Use it when complex reasoning or some
+ cache memory is needed.
+
+ Args:
+ thought (str): A thought to think about.
+
+ Returns:
+ str: The full log of thoughts including the new thought.
+ """
+ try:
+ logger.debug(f"Thought: {thought}")
+ self.thoughts.append(thought)
+
+ thoughts = "\n".join([f"- {t}" for t in self.thoughts])
+ return f"Thoughts:\n{thoughts}"
+
+ except Exception as e:
+ error_msg = f"Error recording thought: {e}"
+ logger.error(error_msg)
+ return error_msg
+
+ def get_tools(self) -> List[FunctionTool]:
+ r"""Get all tools in the toolkit.
+
+ Returns:
+ List[FunctionTool]: A list of tools.
+ """
+ return [FunctionTool(self.think)]
diff --git a/examples/toolkits/thinking_toolkit.py b/examples/toolkits/thinking_toolkit.py
new file mode 100644
index 000000000..fcbf77cbe
--- /dev/null
+++ b/examples/toolkits/thinking_toolkit.py
@@ -0,0 +1,107 @@
+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
+from camel.agents import ChatAgent
+from camel.configs import ChatGPTConfig
+from camel.models import ModelFactory
+from camel.toolkits import ThinkingToolkit
+from camel.types import ModelPlatformType, ModelType
+
+# Initialize model and toolkit
+model = ModelFactory.create(
+ model_platform=ModelPlatformType.DEFAULT,
+ model_type=ModelType.DEFAULT,
+ model_config_dict=ChatGPTConfig().as_dict(),
+)
+
+thinking_toolkit = ThinkingToolkit()
+tools = thinking_toolkit.get_tools()
+
+# Create an agent with the thinking toolkit
+sys_msg = (
+ "You are a helpful assistant that can think through problems "
+ "step by step."
+)
+
+agent = ChatAgent(
+ system_message=sys_msg,
+ model=model,
+ tools=tools,
+)
+
+# Example usage
+usr_msg = (
+ "Help me solve: If a train travels at 60 mph, how long to"
+ "cover 180 miles?"
+)
+
+response = agent.step(usr_msg)
+print(response.msgs[0].content)
+print("\nTool calls:")
+print(response.info['tool_calls'])
+
+"""
+===============================================================================
+The train will take 3 hours to cover 180 miles at a speed of 60 mph.
+
+Tool calls:
+[
+ ToolCallingRecord(
+ tool_name='think',
+ args={
+ 'thought': ('To find the time taken to cover a certain distance at'
+ 'a constant speed, we can use the formula: time = '
+ 'distance / speed. In this case, the distance is 180 '
+ 'miles and the speed is 60 mph.')
+ },
+ result=('Thoughts:\n- To find the time taken to cover a certain '
+ 'distance at a constant speed, we can use the formula: time = '
+ 'distance / speed. In this case, the distance is 180 miles and '
+ 'the speed is 60 mph.'),
+ tool_call_id='call_M6QQ0ymwpVNtpXaacWLhWtqA'
+ ),
+ ToolCallingRecord(
+ tool_name='think',
+ args={
+ 'thought': ('Now, substituting the values into the formula: time ='
+ '180 miles / 60 mph. This can be calculated to find the '
+ 'time in hours.')
+ },
+ result=('Thoughts:\n- To find the time taken to cover a certain '
+ 'distance at a constant speed, we can use the formula: time = '
+ 'distance / speed. In this case, the distance is 180 miles and '
+ 'the speed is 60 mph.\n- Now, substituting the values into the '
+ 'formula: time = 180 miles / 60 mph. This can be calculated to '
+ 'find the time in hours.'),
+ tool_call_id='call_7CXZctOm3BbBaSq1YeCNql45'
+ ),
+ ToolCallingRecord(
+ tool_name='think',
+ args={
+ 'thought': ('Calculating: time = 180 / 60 = 3 hours. Therefore, it'
+ 'will take the train 3 hours to cover 180 miles at a '
+ 'speed of 60 mph.')
+ },
+ result=('Thoughts:\n- To find the time taken to cover a certain '
+ 'distance at a constant speed, we can use the formula: time = '
+ 'distance / speed. In this case, the distance is 180 miles and '
+ 'the speed is 60 mph.\n- Now, substituting the values into the '
+ 'formula: time = 180 miles / 60 mph. This can be calculated to '
+ 'find the time in hours.\n- Calculating: time = 180 / 60 = 3 '
+ 'hours. Therefore, it will take the train 3 hours to cover 180 '
+ 'miles at a speed of 60 mph.'),
+ tool_call_id='call_n1SOosiFYvl2pO6yuq9dLhQb'
+ )
+]
+===============================================================================
+"""
diff --git a/test/toolkits/test_thinking_toolkit.py b/test/toolkits/test_thinking_toolkit.py
new file mode 100644
index 000000000..83b71838c
--- /dev/null
+++ b/test/toolkits/test_thinking_toolkit.py
@@ -0,0 +1,72 @@
+# ========= 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 pytest
+
+from camel.toolkits import ThinkingToolkit
+
+
+def thinking_toolkit():
+ r"""Create a ThinkingToolkit instance for testing."""
+ return ThinkingToolkit()
+
+
+def test_toolkit_initialization(thinking_toolkit):
+ r"""Test if the toolkit is initialized correctly."""
+ assert hasattr(thinking_toolkit, 'thoughts')
+ assert isinstance(thinking_toolkit.thoughts, list)
+ assert len(thinking_toolkit.thoughts) == 0
+
+
+def test_get_tools(thinking_toolkit):
+ r"""Test getting available tools from ThinkingToolkit."""
+ tools = thinking_toolkit.get_tools()
+ assert len(tools) == 1
+ assert tools[0].get_function_name() == "think"
+
+
+def test_think_method(thinking_toolkit):
+ r"""Test the think method."""
+ thought = "This is a test thought"
+ result = thinking_toolkit.think(thought)
+
+ assert isinstance(result, str)
+ assert "Thoughts:" in result
+ assert thought in result
+ assert len(thinking_toolkit.thoughts) == 1
+ assert thinking_toolkit.thoughts[0] == thought
+
+
+def test_multiple_thoughts(thinking_toolkit):
+ r"""Test recording multiple thoughts."""
+ thoughts = ["First thought", "Second thought", "Third thought"]
+
+ for thought in thoughts:
+ result = thinking_toolkit.think(thought)
+ assert thought in result
+
+ assert len(thinking_toolkit.thoughts) == len(thoughts)
+ for thought in thoughts:
+ assert thought in thinking_toolkit.thoughts
+
+
+def test_empty_thought(thinking_toolkit):
+ r"""Test handling of empty thought."""
+ result = thinking_toolkit.think("")
+ assert isinstance(result, str)
+ assert len(thinking_toolkit.thoughts) == 1
+
+
+if __name__ == "__main__":
+ pytest.main([__file__])