Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions camel/toolkits/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,22 @@
class BaseToolkit(metaclass=AgentOpsMeta):
def get_tools(self) -> List[OpenAIFunction]:
raise NotImplementedError("Subclasses must implement this method.")

def list_tools(self) -> List[str]:
r"""Retrieve a list of tool names available in the current class."""
tools = self.get_tools()
tool_names = [tool.func.__name__ for tool in tools]
return tool_names

def get_a_tool(self, func_name: str) -> List[OpenAIFunction]:
r"""Retrieve a tool by its function name if it exists within the
current class.
"""
tools = self.get_tools()
for tool in tools:
if tool.func.__name__ == func_name:
return [tool]
raise AttributeError(
f"{func_name} is not a valid tool name or is not part of "
f"{self.__class__.__name__}'s module."
)
76 changes: 76 additions & 0 deletions examples/toolkits/get_a_tool_from_a_tookit.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
# =========== Copyright 2023 @ 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 @ CAMEL-AI.org. All Rights Reserved. ===========
from camel.agents import ChatAgent
from camel.configs.openai_config import ChatGPTConfig
from camel.messages import BaseMessage
from camel.models import ModelFactory
from camel.toolkits.search_toolkit import SearchToolkit
from camel.toolkits.weather_toolkit import WeatherToolkit
from camel.types import ModelPlatformType, ModelType

print(WeatherToolkit().list_tools())
print(SearchToolkit().list_tools())
'''
===============================================================================
['get_weather_data']
['search_wiki', 'search_duckduckgo', 'search_google', 'query_wolfram_alpha']
===============================================================================
'''

# Define system message
sys_msg = BaseMessage.make_assistant_message(
role_name='Tools calling opertor', content='You are a helpful assistant'
)

# Get one tool from one tookit
tools = WeatherToolkit().get_a_tool('get_weather_data')

# Set model config
model_config_dict = ChatGPTConfig(
temperature=0.0,
).as_dict()

model = ModelFactory.create(
model_platform=ModelPlatformType.OPENAI,
model_type=ModelType.GPT_4O,
model_config_dict=model_config_dict,
)

# Set agent
camel_agent = ChatAgent(
system_message=sys_msg,
model=model,
tools=tools,
)
camel_agent.reset()

# Define a user message
usr_msg = BaseMessage.make_user_message(
role_name='CAMEL User', content='help me to know the weather in London.'
)

# Get response information
response = camel_agent.step(usr_msg)
print(response.info['tool_calls'])
"""
===============================================================================
[FunctionCallingRecord(func_name='get_weather_data', args={'city':
'London, GB', 'temp_units': 'celsius', 'wind_units': 'miles_hour',
'visibility_units': 'miles', 'time_units': 'iso'}, result='Weather
in London, GB: 9.25°Celsius, feels like 7.28°Celsius. Max temp:
10.1°Celsius, Min temp: 8.19°Celsius. Wind: 8.052984 miles_hour
at 320 degrees. Visibility: 6.21 miles. Sunrise at 2024-10-10
06:16:21+00:00, Sunset at 2024-10-10 17:18:10+00:00.')]
===============================================================================
"""
64 changes: 64 additions & 0 deletions test/toolkits/test_base_tookit.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
# =========== Copyright 2023 @ 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 @ CAMEL-AI.org. All Rights Reserved. ===========
import importlib
import os
from unittest.mock import MagicMock, patch

import pytest
from github import Auth, Github

# Note: `OpenAPIToolkit` does not inherit from `BaseToolkit`, so it cannot
# use the `list_tools` and `get_a_tool` functions.
MODULE_NAMES = [
'GithubToolkit',
'MathToolkit',
'GoogleMapsToolkit',
'SearchToolkit',
'SlackToolkit',
'DalleToolkit',
'TwitterToolkit',
'WeatherToolkit',
'RetrievalToolkit',
'LinkedInToolkit',
'RedditToolkit',
'CodeExecutionToolkit',
]


@patch.object(Github, '__init__', lambda self, *args, **kwargs: None)
@patch.object(Github, 'get_repo', return_value=MagicMock())
@patch.object(Auth.Token, '__init__', lambda self, *args, **kwargs: None)
@pytest.mark.parametrize("module_name", MODULE_NAMES)
def test_toolkits(mock_get_repo, module_name):
with patch.dict(os.environ, {"GITHUB_ACCESS_TOKEN": "fake_token"}):
toolkit_class = getattr(
importlib.import_module('camel.toolkits'), module_name
)

if module_name == 'GithubToolkit':
toolkit = toolkit_class('camel-ai/camel')
else:
toolkit = toolkit_class()

tool_names = toolkit.list_tools()

for tool_name in tool_names:
tool = toolkit.get_a_tool(tool_name)
assert (
tool
), f"Tool {tool_name} could not be retrieved in {module_name}"
assert tool[0].func.__name__ == tool_name, (
f"Retrieved tool's function name {tool[0].func.__name__}"
f"does not match {tool_name}"
)
Loading