🐫 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
feat: ACI_Tool_interface (#2295)
Saed Bhatiefcd5ae202eb
diff --git a/.env b/.envindex 07cfe4c58..01528a484 100644--- a/.env+++ b/.env@@ -111,4 +111,8 @@# BOCHA_API_KEY="Fill your API key here"# Klavis AI API (https://www.klavis.ai)-# KLAVIS_API_KEY="Fill your API key here"\ No newline at end of file+# KLAVIS_API_KEY="Fill your API key here"++# ACI API (https://platform.aci.dev/)+# ACI_API_KEY="Fill your API key here"+# LINKED_ACCOUNT_OWNER="Fill your Linked Account Owner here"diff --git a/.github/workflows/build_package.yml b/.github/workflows/build_package.ymlindex abc5e792b..4f71c02e2 100644--- a/.github/workflows/build_package.yml+++ b/.github/workflows/build_package.yml@@ -136,6 +136,7 @@ jobs:NOVITA_API_KEY: "${{ secrets.NOVITA_API_KEY }}"WATSONX_API_KEY: "${{ secrets.WATSONX_API_KEY }}"WATSONX_PROJECT_ID: "${{ secrets.WATSONX_PROJECT_ID }}"+ ACI_API_KEY: "${{ secrets.ACI_API_KEY }}"run: |source test_venv/bin/activatepytest --fast-test-mode ./testdiff --git a/.github/workflows/pytest_package.yml b/.github/workflows/pytest_package.ymlindex fc623e813..8f4cffd52 100644--- a/.github/workflows/pytest_package.yml+++ b/.github/workflows/pytest_package.yml@@ -75,6 +75,7 @@ jobs:NOVITA_API_KEY: "${{ secrets.NOVITA_API_KEY }}"WATSONX_API_KEY: "${{ secrets.WATSONX_API_KEY }}"WATSONX_PROJECT_ID: "${{ secrets.WATSONX_PROJECT_ID }}"+ ACI_API_KEY: "${{ secrets.ACI_API_KEY }}"run: |source .venv/bin/activateuv pip install -e ".[all, dev, docs]"@@ -142,6 +143,7 @@ jobs:NOVITA_API_KEY: "${{ secrets.NOVITA_API_KEY }}"WATSONX_API_KEY: "${{ secrets.WATSONX_API_KEY }}"WATSONX_PROJECT_ID: "${{ secrets.WATSONX_PROJECT_ID }}"+ ACI_API_KEY: "${{ secrets.ACI_API_KEY }}"run: |source .venv/bin/activateuv pip install -e ".[all, dev, docs]"@@ -207,6 +209,7 @@ jobs:NOVITA_API_KEY: "${{ secrets.NOVITA_API_KEY }}"WATSONX_API_KEY: "${{ secrets.WATSONX_API_KEY }}"WATSONX_PROJECT_ID: "${{ secrets.WATSONX_PROJECT_ID }}"+ ACI_API_KEY: "${{ secrets.ACI_API_KEY }}"run: |source .venv/bin/activateuv pip install -e ".[all, dev, docs]"diff --git a/camel/toolkits/__init__.py b/camel/toolkits/__init__.pyindex 1df14d274..e96cfbe8b 100644--- a/camel/toolkits/__init__.py+++ b/camel/toolkits/__init__.py@@ -69,6 +69,7 @@ from .openai_agent_toolkit import OpenAIAgentToolkitfrom .searxng_toolkit import SearxNGToolkitfrom .jina_reranker_toolkit import JinaRerankerToolkitfrom .klavis_toolkit import KlavisToolkit+from .aci_toolkit import ACIToolkit__all__ = [@@ -126,4 +127,5 @@ __all__ = ['SearxNGToolkit','JinaRerankerToolkit','KlavisToolkit',+ 'ACIToolkit',]diff --git a/camel/toolkits/aci_toolkit.py b/camel/toolkits/aci_toolkit.pynew file mode 100644index 000000000..7f9ef69d1--- /dev/null+++ b/camel/toolkits/aci_toolkit.py@@ -0,0 +1,456 @@+# ========= 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 os+from typing import TYPE_CHECKING, Dict, List, Optional, Union++if TYPE_CHECKING:+ from aci.types.app_configurations import AppConfiguration+ from aci.types.apps import AppBasic, AppDetails+ from aci.types.linked_accounts import LinkedAccount++from camel.logger import get_logger+from camel.toolkits import FunctionTool+from camel.toolkits.base import BaseToolkit+from camel.utils import api_keys_required, dependencies_required++logger = get_logger(__name__)+++@api_keys_required(+ [+ (None, 'ACI_API_KEY'),+ ]+)+class ACIToolkit(BaseToolkit):+ r"""A toolkit for interacting with the ACI API."""++ @dependencies_required('aci')+ def __init__(+ self,+ api_key: Optional[str] = None,+ base_url: Optional[str] = None,+ linked_account_owner_id: Optional[str] = None,+ timeout: Optional[float] = None,+ ) -> None:+ r"""Initialize the ACI toolkit.++ Args:+ api_key (Optional[str]): The API key for authentication.+ (default: :obj: `None`)+ base_url (Optional[str]): The base URL for the ACI API.+ (default: :obj: `None`)+ linked_account_owner_id (Optional[str]): ID of the owner of the+ linked account, e.g., "johndoe"+ (default: :obj: `None`)+ timeout (Optional[float]): Request timeout.+ (default: :obj: `None`)+ """+ from aci import ACI++ super().__init__(timeout)++ self._api_key = api_key or os.getenv("ACI_API_KEY")+ self._base_url = base_url or os.getenv("ACI_BASE_URL")+ self.client = ACI(api_key=self._api_key, base_url=self._base_url)+ self.linked_account_owner_id = linked_account_owner_id++ def search_tool(+ self,+ intent: Optional[str] = None,+ allowed_app_only: bool = True,+ include_functions: bool = False,+ categories: Optional[List[str]] = None,+ limit: Optional[int] = 10,+ offset: Optional[int] = 0,+ ) -> Union[List["AppBasic"], str]:+ r"""Search for apps based on intent.++ Args:+ intent (Optional[str]): Search results will be sorted by relevance+ to this intent.+ (default: :obj: `None`)+ allowed_app_only (bool): If true, only return apps that+ are allowed by the agent/accessor, identified by the api key.+ (default: :obj: `True`)+ include_functions (bool): If true, include functions+ (name and description) in the search results.+ (default: :obj: `False`)+ categories (Optional[List[str]]): List of categories to filter the+ search results. Defaults to an empty list.+ (default: :obj: `None`)+ limit (Optional[int]): Maximum number of results to return.+ (default: :obj: `10`)+ offset (Optional[int]): Offset for pagination.+ (default: :obj: `0`)++ Returns:+ Optional[List[AppBasic]]: List of matching apps if successful,+ error message otherwise.+ """+ try:+ apps = self.client.apps.search(+ intent=intent,+ allowed_apps_only=allowed_app_only,+ include_functions=include_functions,+ categories=categories,+ limit=limit,+ offset=offset,+ )+ return apps+ except Exception as e:+ logger.error(f"Error: {e}")+ return str(e)++ def list_configured_apps(+ self,+ app_names: Optional[List[str]] = None,+ limit: Optional[int] = 10,+ offset: Optional[int] = 0,+ ) -> Union[List["AppConfiguration"], str]:+ r"""List all configured apps.++ Args:+ app_names (Optional[List[str]]): List of app names to filter the+ results. (default: :obj: `None`)+ limit (Optional[int]): Maximum number of results to return.+ (default: :obj: `10`)+ offset (Optional[int]): Offset for pagination. (default: :obj: `0`)++ Returns:+ Union[List[AppConfiguration], str]: List of configured apps if+ successful, error message otherwise.+ """+ try:+ apps = self.client.app_configurations.list(+ app_names=app_names, limit=limit, offset=offset+ )+ return apps+ except Exception as e:+ logger.error(f"Error: {e}")+ return str(e)++ def configure_app(self, app_name: str) -> Union[Dict, str]:+ r"""Configure an app with specified authentication type.++ Args:+ app_name (str): Name of the app to configure.++ Returns:+ Union[Dict, str]: Configuration result or error message.+ """+ from aci.types.enums import SecurityScheme++ try:+ app_details = self.get_app_details(app_name)+ if app_details and app_details.security_schemes[0] == "api_key":+ security_scheme = SecurityScheme.API_KEY+ elif app_details and app_details.security_schemes[0] == "oauth2":+ security_scheme = SecurityScheme.OAUTH2+ else:+ security_scheme = SecurityScheme.NO_AUTH+ configuration = self.client.app_configurations.create(+ app_name=app_name, security_scheme=security_scheme+ )+ return configuration+ except Exception as e:+ logger.error(f"Error: {e}")+ return str(e)++ def get_app_configuration(+ self, app_name: str+ ) -> Union["AppConfiguration", str]:+ r"""Get app configuration by app name.++ Args:+ app_name (str): Name of the app to get configuration for.++ Returns:+ Union[AppConfiguration, str]: App configuration if successful,+ error message otherwise.+ """+ try:+ app = self.client.app_configurations.get(app_name=app_name)+ return app+ except Exception as e:+ logger.error(f"Error: {e}")+ return str(e)++ def delete_app(self, app_name: str) -> Optional[str]:+ r"""Delete an app configuration.++ Args:+ app_name (str): Name of the app to delete.++ Returns:+ Optional[str]: None if successful, error message otherwise.+ """+ try:+ self.client.app_configurations.delete(app_name=app_name)+ return None+ except Exception as e:+ logger.error(f"Error: {e}")+ return str(e)++ def link_account(+ self,+ app_name: str,+ ) -> Union["LinkedAccount", str]:+ r"""Link an account to a configured app.++ Args:+ app_name (str): Name of the app to link the account to.++ Returns:+ Union[LinkedAccount, str]: LinkedAccount object if successful,+ error message otherwise.+ """+ from aci.types.enums import SecurityScheme++ try:+ security_scheme = self.client.app_configurations.get(+ app_name=app_name+ ).security_scheme++ if security_scheme == SecurityScheme.API_KEY:+ return self.client.linked_accounts.link(+ app_name=app_name,+ linked_account_owner_id=self.linked_account_owner_id,+ security_scheme=security_scheme,+ api_key=self._api_key,+ )+ else:+ return self.client.linked_accounts.link(+ app_name=app_name,+ linked_account_owner_id=self.linked_account_owner_id,+ security_scheme=security_scheme,+ )+ except Exception as e:+ logger.error(f"Error linking account: {e!s}")+ return str(e)++ def get_app_details(self, app_name: str) -> "AppDetails":+ r"""Get details of an app.++ Args:+ app_name (str): Name of the app to get details for.++ Returns:+ AppDetails: App details.+ """+ app = self.client.apps.get(app_name=app_name)+ return app++ def get_linked_accounts(+ self, app_name: str+ ) -> Union[List["LinkedAccount"], str]:+ r"""List all linked accounts for a specific app.++ Args:+ app_name (str): Name of the app to get linked accounts for.++ Returns:+ Union[List[LinkedAccount], str]: List of linked accounts if+ successful, error message otherwise.+ """+ try:+ accounts = self.client.linked_accounts.list(app_name=app_name)+ return accounts+ except Exception as e:+ logger.error(f"Error: {e}")+ return str(e)++ def enable_linked_account(+ self, linked_account_id: str+ ) -> Union["LinkedAccount", str]:+ r"""Enable a linked account.++ Args:+ linked_account_id (str): ID of the linked account to enable.++ Returns:+ Union[LinkedAccount, str]: Linked account if successful, error+ message otherwise.+ """+ try:+ linked_account = self.client.linked_accounts.enable(+ linked_account_id=linked_account_id+ )+ return linked_account+ except Exception as e:+ logger.error(f"Error: {e}")+ return str(e)++ def disable_linked_account(+ self, linked_account_id: str+ ) -> Union["LinkedAccount", str]:+ r"""Disable a linked account.++ Args:+ linked_account_id (str): ID of the linked account to disable.++ Returns:+ Union[LinkedAccount, str]: The updated linked account if+ successful, error message otherwise.+ """+ try:+ linked_account = self.client.linked_accounts.disable(+ linked_account_id=linked_account_id+ )+ return linked_account+ except Exception as e:+ logger.error(f"Error: {e}")+ return str(e)++ def delete_linked_account(self, linked_account_id: str) -> str:+ r"""Delete a linked account.++ Args:+ linked_account_id (str): ID of the linked account to delete.++ Returns:+ str: Success message if successful, error message otherwise.+ """+ try:+ self.client.linked_accounts.delete(+ linked_account_id=linked_account_id+ )+ return (+ f"linked_account_id: {linked_account_id} deleted successfully"+ )+ except Exception as e:+ logger.error(f"Error: {e}")+ return str(e)++ def function_definition(self, func_name: str) -> Dict:+ r"""Get the function definition for an app.++ Args:+ app_name (str): Name of the app to get function definition for++ Returns:+ Dict: Function definition dictionary.+ """+ return self.client.functions.get_definition(func_name)++ def search_function(+ self,+ app_names: Optional[List[str]] = None,+ intent: Optional[str] = None,+ allowed_apps_only: bool = True,+ limit: Optional[int] = 10,+ offset: Optional[int] = 0,+ ) -> List[Dict]:+ r"""Search for functions based on intent.++ Args:+ app_names (Optional[List[str]]): List of app names to filter the+ search results. (default: :obj: `None`)+ intent (Optional[str]): The search query/intent.+ (default: :obj: `None`)+ allowed_apps_only (bool): If true, only return+ functions from allowed apps. (default: :obj: `True`)+ limit (Optional[int]): Maximum number of results to return.+ (default: :obj: `10`)+ offset (Optional[int]): Offset for pagination.+ (default: :obj: `0`)++ Returns:+ List[Dict]: List of matching functions+ """+ return self.client.functions.search(+ app_names=app_names,+ intent=intent,+ allowed_apps_only=allowed_apps_only,+ limit=limit,+ offset=offset,+ )++ def execute_function(+ self,+ function_name: str,+ function_arguments: Dict,+ linked_account_owner_id: str,+ allowed_apps_only: bool = False,+ ) -> Dict:+ r"""Execute a function call.++ Args:+ function_name (str): Name of the function to execute.+ function_arguments (Dict): Arguments to pass to the function.+ linked_account_owner_id (str): To specify the end-user (account+ owner) on behalf of whom you want to execute functions+ You need to first link corresponding account with the same+ owner id in the ACI dashboard (https://platform.aci.dev).+ allowed_apps_only (bool): If true, only returns functions/apps+ that are allowed to be used by the agent/accessor, identified+ by the api key. (default: :obj: `False`)++ Returns:+ Dict: Result of the function execution+ """+ result = self.client.handle_function_call(+ function_name,+ function_arguments,+ linked_account_owner_id,+ allowed_apps_only,+ )+ return result++ def get_tools(self) -> List[FunctionTool]:+ r"""Get a list of tools (functions) available in the configured apps.++ Returns:+ List[FunctionTool]: List of FunctionTool objects representing+ available functions+ """+ _configure_app = [+ app.app_name # type: ignore[union-attr]+ for app in self.list_configured_apps() or []+ ]+ _all_function = self.search_function(app_names=_configure_app)+ tools = [+ FunctionTool(self.search_tool),+ FunctionTool(self.list_configured_apps),+ FunctionTool(self.configure_app),+ FunctionTool(self.get_app_configuration),+ FunctionTool(self.delete_app),+ FunctionTool(self.link_account),+ FunctionTool(self.get_app_details),+ FunctionTool(self.get_linked_accounts),+ FunctionTool(self.enable_linked_account),+ FunctionTool(self.disable_linked_account),+ FunctionTool(self.delete_linked_account),+ FunctionTool(self.function_definition),+ FunctionTool(self.search_function),+ ]++ for function in _all_function:+ schema = self.client.functions.get_definition(+ function['function']['name']+ )++ def dummy_func(*, schema=schema, **kwargs):+ return self.execute_function(+ function_name=schema['function']['name'],+ function_arguments=kwargs,+ linked_account_owner_id=self.linked_account_owner_id,+ )++ tool = FunctionTool(+ func=dummy_func,+ openai_tool_schema=schema,+ )+ tools.append(tool)+ return toolsdiff --git a/examples/single_agent.py b/examples/agents/single_agent.pysimilarity index 100%rename from examples/single_agent.pyrename to examples/agents/single_agent.pydiff --git a/examples/test/test_babyagi_example.py b/examples/test/test_babyagi_example.pyindex 7c1703fd1..1a0a21b7e 100644--- a/examples/test/test_babyagi_example.py+++ b/examples/test/test_babyagi_example.py@@ -12,10 +12,11 @@# limitations under the License.# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========import pytest-from mock import patch+from mock import MagicMock, patchimport examples.ai_society.babyagi_playingfrom camel.models import ModelFactory+from camel.societies.babyagi_playing import BabyAGIfrom camel.types import ModelPlatformType, ModelTypeparametrize = pytest.mark.parametrize(@@ -32,7 +33,164 @@ parametrize = pytest.mark.parametrize(@parametrizedef test_ai_society_babyagi_playing_example(model):- with patch('time.sleep', return_value=None):- examples.ai_society.babyagi_playing.main(- model=model, chat_turn_limit=2+ r"""Test that the BabyAGI example structure works without actually running+ the resource-intensive parts.+ """+ # Mock BabyAGI to avoid actual instantiation and execution+ with patch(+ 'examples.ai_society.babyagi_playing.BabyAGI'+ ) as mock_babyagi_class:+ mock_babyagi_instance = MagicMock()+ mock_babyagi_class.return_value = mock_babyagi_instance+ mock_response = MagicMock()+ mock_response.terminated = True+ mock_response.info = {+ 'termination_reasons': 'Test completed',+ 'task_name': 'Test',+ 'subtasks': [],+ }+ mock_response.msg = MagicMock()+ mock_babyagi_instance.step.return_value = mock_response++ # Mock print functions to avoid console output+ with patch('examples.ai_society.babyagi_playing.print_text_animated'):+ with patch('examples.ai_society.babyagi_playing.print'):+ # Run the main function with our mocks+ examples.ai_society.babyagi_playing.main(+ model=model, chat_turn_limit=2+ )++ mock_babyagi_class.assert_called_once()+ assert mock_babyagi_instance.step.called+++@parametrize+def test_babyagi_initialization(model):+ r"""Test that BabyAGI initializes with correct parameters."""+ task_prompt = "Test task prompt"+ assistant_role = "Test Assistant"+ user_role = "Test User"++ # Mock the TaskSpecifyAgent to avoid actual API calls+ with patch(+ 'camel.societies.babyagi_playing.TaskSpecifyAgent'+ ) as mock_task_specify_agent_class:+ # Create a mock instance and mock the run method+ mock_task_specify_agent = MagicMock()+ mock_task_specify_agent_class.return_value = mock_task_specify_agent+ mock_task_specify_agent.run.return_value = "Specified test task"++ # Mock the SystemMessageGenerator to avoid actual API calls+ with patch(+ 'camel.societies.babyagi_playing.SystemMessageGenerator'+ ) as mock_sys_msg_generator_class:+ # Create a mock instance and mock the from_dicts method+ mock_sys_msg_generator = MagicMock()+ mock_sys_msg_generator_class.return_value = mock_sys_msg_generator+ mock_sys_msg = [MagicMock()]+ mock_sys_msg_generator.from_dicts.return_value = mock_sys_msg++ # Mock ChatAgent to avoid actual API calls+ with patch(+ 'camel.societies.babyagi_playing.ChatAgent'+ ) as mock_chat_agent_class:+ mock_chat_agent = MagicMock()+ mock_chat_agent.model = model+ mock_chat_agent_class.return_value = mock_chat_agent++ babyagi = BabyAGI(+ assistant_role_name=assistant_role,+ assistant_agent_kwargs=dict(model=model),+ user_role_name=user_role,+ task_prompt=task_prompt,+ task_specify_agent_kwargs=dict(model=model),+ )++ assert babyagi.task_prompt == task_prompt+ assert mock_task_specify_agent.run.called+ assert mock_sys_msg_generator.from_dicts.called+++@parametrize+def test_babyagi_step_functionality(model):+ r"""Test that BabyAGI step method works as expected."""+ with patch(+ 'examples.ai_society.babyagi_playing.BabyAGI'+ ) as mock_babyagi_class:+ mock_babyagi = MagicMock()+ mock_babyagi_class.return_value = mock_babyagi++ # Create a mock response for the step method+ mock_response = MagicMock()+ mock_response.terminated = False+ mock_response.msg = MagicMock()+ mock_response.msg.content = "Test response content"+ mock_response.info = {+ 'task_name': 'Test Task',+ 'subtasks': ['Subtask 1', 'Subtask 2'],+ }+ mock_babyagi.step.return_value = mock_response++ # Mock print functions to avoid console output+ with patch('examples.ai_society.babyagi_playing.print_text_animated'):+ with patch('examples.ai_society.babyagi_playing.print'):+ # Run the main function with our mocks+ examples.ai_society.babyagi_playing.main(+ model=model, chat_turn_limit=1+ )++ # Verify BabyAGI was instantiated with expected parameters+ mock_babyagi_class.assert_called_once_with(+ assistant_role_name="Python Programmer",+ assistant_agent_kwargs=dict(model=model),+ user_role_name="Stock Trader",+ task_prompt="Develop a trading bot for the stock market",+ task_specify_agent_kwargs=dict(model=model),)++ assert mock_babyagi.step.called+++@parametrize+def test_babyagi_termination(model):+ r"""Test that BabyAGI terminates correctly when response indicates+ termination.+ """+ with patch(+ 'examples.ai_society.babyagi_playing.BabyAGI'+ ) as mock_babyagi_class:+ mock_babyagi = MagicMock()+ mock_babyagi_class.return_value = mock_babyagi++ # Create a mock response that indicates termination+ mock_response = MagicMock()+ mock_response.terminated = True+ mock_response.msg = MagicMock()+ mock_response.msg.content = "Final task completed"+ mock_response.info = {+ 'termination_reasons': 'Task completed',+ 'task_name': 'Final Task',+ 'subtasks': [],+ }+ mock_babyagi.step.return_value = mock_response++ # Mock print functions to avoid console output+ with patch('examples.ai_society.babyagi_playing.print_text_animated'):+ with patch('examples.ai_society.babyagi_playing.print'):+ # Run the main function with our mocks+ # Set a high chat_turn_limit to verify early termination+ examples.ai_society.babyagi_playing.main(+ model=model, chat_turn_limit=10+ )++ # Verify BabyAGI was instantiated with expected parameters+ mock_babyagi_class.assert_called_once()++ # Verify step was called exactly once (since it should terminate after+ # first step)+ mock_babyagi.step.assert_called_once()++ # Test the termination condition+ response = mock_babyagi.step.return_value+ assert response.terminated+ assert 'termination_reasons' in response.infodiff --git a/examples/toolkits/aci_toolkit.py b/examples/toolkits/aci_toolkit.pynew file mode 100644index 000000000..cab351347--- /dev/null+++ b/examples/toolkits/aci_toolkit.py@@ -0,0 +1,64 @@+# ========= 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 os++from dotenv import load_dotenv++from camel.agents import ChatAgent+from camel.models import ModelFactory+from camel.toolkits import ACIToolkit+from camel.types import ModelPlatformType, ModelType++load_dotenv()++LINKED_ACCOUNT_OWNER = os.getenv("LINKED_ACCOUNT_OWNER")++if LINKED_ACCOUNT_OWNER is None:+ raise ValueError("LINKED_ACCOUNT_owner environment variable is not set.")++# Create ACIToolkit with GitHub permissions+aci_toolkit = ACIToolkit(linked_account_owner_id=LINKED_ACCOUNT_OWNER)++model = ModelFactory.create(+ model_platform=ModelPlatformType.DEFAULT,+ model_type=ModelType.DEFAULT,+)++# Create ChatAgent with GitHub tools+chat_agent = ChatAgent(+ model=model,+ tools=aci_toolkit.get_tools(), # Explicitly allow GitHub app+)++response = chat_agent.step("star the repo camel-ai/camel")+print(response)++"""+==============================================================================+msgs=[BaseMessage(role_name='assistant', role_type=<RoleType.ASSISTANT:+'assistant'>, meta_dict={}, content='The repository **camel-ai/camel** has+been successfully starred!', video_bytes=None, image_list=None,+image_detail='auto', video_detail='low', parsed=None)] terminated=False info=+{'id': 'chatcmpl-BTb0Qd0RUFWkIz96WPWzKkhTEx4GZ', 'usage':+{'completion_tokens': 15, 'prompt_tokens': 1323, 'total_tokens': 1338,+'completion_tokens_details': {'accepted_prediction_tokens': 0, 'audio_tokens':+0, 'reasoning_tokens': 0, 'rejected_prediction_tokens': 0},+'prompt_tokens_details': {'audio_tokens': 0, 'cached_tokens': 1280}},+'termination_reasons': ['stop'], 'num_tokens': 57, 'tool_calls':+[ToolCallingRecord(tool_name='GITHUB__STAR_REPOSITORY', args={'path': {'repo':+'camel', 'owner': 'camel-ai'}}, result={'success': True, 'data': {}},+tool_call_id='call_5jlmAN7VKEq1Pc9kppWBJvoZ')], 'external_tool_call_requests':+None}+==============================================================================+"""diff --git a/examples/toolkits/semantic_scholar_toolkit.py b/examples/toolkits/semantic_scholar_toolkit.pyindex a8a8b4864..eafc4d4f4 100644--- a/examples/toolkits/semantic_scholar_toolkit.py+++ b/examples/toolkits/semantic_scholar_toolkit.py@@ -1,320 +1,320 @@-# ========= 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 SemanticScholarToolkit-from camel.types import ModelPlatformType, ModelType--# Define the model, here in this case we use gpt-4o-model = ModelFactory.create(- model_platform=ModelPlatformType.DEFAULT,- model_type=ModelType.DEFAULT,- model_config_dict=ChatGPTConfig(temperature=0.0).as_dict(),-)---sys_msg = "You are a helpful assistant"--# Initialize a toolkit-toolkit = SemanticScholarToolkit()-# Get list of tools-tools = toolkit.get_tools()--# Initialize a ChatAgent with your custom tools-camel_agent = ChatAgent(- system_message=sys_msg,- model=model,- tools=tools,-)--# Description of the added tools-usr_msg = "Describe the tools you've added"--response = camel_agent.step(usr_msg)-print(response.msgs[0].content)--'''-================================================================-1. **fetch_paper_data_title**: This tool fetches a single paper- based on its title. You can specify which fields to include in- the response, such as the abstract, authors, year, citation- count, and more.--2. **fetch_paper_data_id**: Similar to the previous tool,- this one retrieves a single paper but uses a paper ID instead- of the title. It also allows for specifying the fields to- include in the response.--3. **fetch_bulk_paper_data**: This tool allows you to fetch- multiple papers at once based on a query that can include- various operators (like AND, OR, NOT). You can filter by- year and specify which fields to return.--4. **fetch_recommended_papers**: This tool provides- recommendations for papers based on a list of positively- and negatively correlated paper IDs. You can specify the- fields to include in the response and limit the number- of papers returned.--5. **fetch_author_data**: This tool retrieves information- about authors based on their IDs. You can specify which- fields to include in the response, such as the author's name,- URL, paper count, h-index, and their papers.--These tools can be used individually or in combination to- gather comprehensive information about academic literature- and authors.-================================================================-'''--# Search a paper through its id-usr_msg = """search the paper 'Construction of the Literature- Graph in Semantic Scholar' for me including its paperid"""-camel_agent.reset()-response = camel_agent.step(usr_msg)-print(str(response.info['tool_calls'])[:1000])--'''-================================================================-[FunctionCallingRecord(func_name='fetch_paper_data_title',-args={'paperTitle': 'Construction of the Literature Graph in-Semantic Scholar', 'fields': 'title,abstract,authors,year,-citationCount,paperId'}, result={'total': 1, 'offset': 0,-'data': [{'paperId': '649def34f8be52c8b66281af98ae884c09aef38b',-'title': 'Construction of the Literature Graph in Semantic- Scholar', 'abstract': 'We describe a deployed scalable system-for organizing published scientific literature into a-heterogeneous graph to facilitate algorithmic manipulation and-discovery. The resulting literature graph consists of more than- 280M nodes, representing papers, authors, entities and various- interactions between them (e.g., authorships, citations,- entity mentions). We reduce literature graph construction into- familiar NLP tasks (e.g., entity extraction and linking),- point out research challenges due to differences from standard- formulations of these tasks, and report empirical results for- each task. The methods describe-================================================================-'''--# Search a paper through its title-usr_msg = """search the paper with paper id of- '649def34f8be52c8b66281af98ae884c09aef38b' for me"""-camel_agent.reset()-response = camel_agent.step(usr_msg)-print(str(response.info['tool_calls'])[:1000])--'''-================================================================-[FunctionCallingRecord(func_name='fetch_paper_data_id', args=-{'paperID': '649def34f8be52c8b66281af98ae884c09aef38b',-'fields': 'title,abstract,authors,year,citationCount,-publicationTypes,publicationDate,openAccessPdf'},-result={'paperId': '649def34f8be52c8b66281af98ae884c09aef38b',-'title': 'Construction of the Literature Graph in Semantic- Scholar', 'abstract': 'We describe a deployed scalable system- for organizing published scientific literature into a- heterogeneous graph to facilitate algorithmic manipulation- and discovery. The resulting literature graph consists of- more than 280M nodes, representing papers, authors, entities- and various interactions between them (e.g., authorships,- citations, entity mentions). We reduce literature graph- construction into familiar NLP tasks (e.g., entity extraction- and linking), point out research challenges due to differences- from standard formulations of these tasks, and report- empirical results for each task. The methods described- in this paper ar-================================================================-'''--# Search papers through related topic-usr_msg = """search 3 papers with topic related to- 'generative ai' from 2024 for me"""-camel_agent.reset()-response = camel_agent.step(usr_msg)-print(str(response.info['tool_calls'])[:1000])--'''-================================================================-[FunctionCallingRecord(func_name='fetch_bulk_paper_data',-args={'query': 'generative ai', 'year': '2024-', 'fields':-'title,url,publicationTypes,publicationDate,openAccessPdf'},-result={'total': 9849, 'token': 'PCOA3RZZB2ADADAEYCX2BLJJRDEGL-PUCFA3I5XJAKEAB3YXPGDOTY2GU3WHI4ZMALUMAPUDPHP724CEUVEFKTYRZY5K-LUU53Y5MWWEINIKYZZRC3YT3H4AF7CTSQ', 'data': [{'paperId':-'0008cd09c0449451b9e6e6de35c29009f0883cd9', 'url': 'https://www-.semanticscholar.org/paper/0008cd09c0449451b9e6e6de35c29009-f0883cd9', 'title': 'A Chitchat on Using ChatGPT for Cheating',- 'openAccessPdf': {'url': 'https://doi.org/10.34074/proc.240106'- , 'status': 'BRONZE'}, 'publicationTypes': ['Conference'],- 'publicationDate': '2024-07-24'}, {'paperId': '0013aecf813400- 174158e4f012918c5408f90962', 'url': 'https://www.semanticsc- holar.org/paper/0013aecf813400174158e4f012918c5408f90962',- 'title': 'Can novice teachers detect AI-generated texts in EFL- writing?', 'openAccessPdf': None, 'publicationTypes':- ['JournalArticle'], 'publicationDate'-================================================================-'''--# Search papers through related topic and operator-usr_msg = """search 2 papers with topic related to- 'ai and bio' from 2024 for me"""-camel_agent.reset()-response = camel_agent.step(usr_msg)-print(str(response.info['tool_calls'])[:1000])--'''-================================================================-[FunctionCallingRecord(func_name='fetch_bulk_paper_data',-args={'query': 'ai and bio', 'year': '2024-', 'fields': 'title,-url,publicationTypes,publicationDate,openAccessPdf'}, result=-{'total': 207, 'token': None, 'data': [{'paperId': '00c8477a9c-c28b85e4f6da13d2a889c94a955291', 'url': 'https://www.semantics-cholar.org/paper/00c8477a9cc28b85e4f6da13d2a889c94a955291',-'title': 'Explaining Enterprise Knowledge Graphs with Large- Language Models and Ontological Reasoning', 'openAccessPdf':- None, 'publicationTypes': ['JournalArticle'], 'publicationDate- ': None}, {'paperId': '01726fbfc8ee716c82b9c4cd70696906d3a4- 46d0', 'url': 'https://www.semanticscholar.org/paper/01726fbfc- 8ee716c82b9c4cd70696906d3a446d0', 'title': 'Study Research- Protocol for Phenome India-CSIR Health Cohort Knowledgebase- (PI-CHeCK): A Prospective multi-modal follow-up study on a- nationwide employee cohort.', 'openAccessPdf': {'url':- 'https://www.medrxiv.org/content/medrxiv/early/2024/10/19/2024- .10.17.24315252.full.pdf', 'status'-================================================================-'''--# Recommend papers through positive and negative paper id-usr_msg = """recommend 2 papers with positive paper id- of "02138d6d094d1e7511c157f0b1a3dd4e5b20ebee",- "018f58247a20ec6b3256fd3119f57980a6f37748" and negative- paper id of "0045ad0c1e14a4d1f4b011c92eb36b8df63d65bc"- for me"""-camel_agent.reset()-response = camel_agent.step(usr_msg)-print(str(response.info['tool_calls'])[:1000])--'''-================================================================-[FunctionCallingRecord(func_name='fetch_recommended_papers',-args={'positive_paper_ids': ['02138d6d094d1e7511c157f0b1a3dd4e-5b20ebee', '018f58247a20ec6b3256fd3119f57980a6f37748'], 'negati-ve_paper_ids': ['0045ad0c1e14a4d1f4b011c92eb36b8df63d65bc'],-'fields': 'title,url,citationCount,authors,publicationTypes,-publicationDate,openAccessPdf', 'limit': 20, 'save_to_file': F-alse}, result={'recommendedPapers': [{'paperId': '9cb202a72171-dc954f8180b42e08da7ab31e16a1', 'url': 'https://www.semanticsc-holar.org/paper/9cb202a72171dc954f8180b42e08da7ab31e16a1', 'tit-le': 'Embrace, Don't Avoid: Reimagining Higher Education with- Generative Artificial Intelligence', 'citationCount': 0, 'op- enAccessPdf': {'url': 'https://heca-analitika.com/jeml/arti- cle/download/233/157', 'status': 'HYBRID'}, 'publicationT- ypes': ['JournalArticle'], 'publicationDate': '2024-11-2- 8', 'authors': [{'authorId': '1659371967', 'name': 'T. R. N- oviandy'}, {'authorId': '1657989613', 'name': 'A. Maulan- a'}, {'authorId': '146805414', 'name-================================================================-'''--# Recommend papers and save the result in a file-usr_msg = """search the authors of author ids of "2281351310",- "2281342663","2300302076","2300141520" for me"""-camel_agent.reset()-response = camel_agent.step(usr_msg)-print(str(response.info['tool_calls'])[:1000])--'''-================================================================-[FunctionCallingRecord(func_name='fetch_recommended_papers',-args={'positive_paper_ids': ['02138d6d094d1e7511c157f0b1a3dd4e5-b20ebee', '018f58247a20ec6b3256fd3119f57980a6f37748'], 'negativ-e_paper_ids': ['0045ad0c1e14a4d1f4b011c92eb36b8df63d65bc'],- 'fields': 'title,url,citationCount,authors,publicationTypes,- publicationDate,openAccessPdf', 'limit': 20, 'save_to_file': T- rue}, result={'recommendedPapers': [{'paperId': '9cb202a7217- 1dc954f8180b42e08da7ab31e16a1', 'url': 'https://www.semantics- cholar.org/paper/9cb202a72171dc954f8180b42e08da7ab31e16a1',- 'title': 'Embrace, Don't Avoid: Reimagining Higher Education- with Generative Artificial Intelligence', 'citationCount':- 0, 'openAccessPdf': {'url': 'https://heca-analitika.com/jeml- /article/download/233/157', 'status': 'HYBRID'}, 'publication- Types': ['JournalArticle'], 'publicationDate': '2024-11-28',- 'authors': [{'authorId': '1659371967', 'name': 'T. R. Novia- ndy'}, {'authorId': '1657989613', 'name': 'A. Maulana'},- {'authorId': '146805414', 'name'-================================================================-'''--# Search author information through author id-usr_msg = """recommend 2 papers with positive paper id- of "02138d6d094d1e7511c157f0b1a3dd4e5b20ebee", "018f5- 8247a20ec6b3256fd3119f57980a6f37748" and negative paper- id of "0045ad0c1e14a4d1f4b011c92eb36b8df63d65bc" for me,- and please save the result in a file."""-camel_agent.reset()-response = camel_agent.step(usr_msg)-print(str(response.info['tool_calls'])[:1000])--'''-================================================================-[FunctionCallingRecord(func_name='fetch_recommended_papers',-args={'positive_paper_ids': ['02138d6d094d1e7511c157f0b1a3dd4e5-b20ebee', '018f58247a20ec6b3256fd3119f57980a6f37748'], 'negat-ive_paper_ids': ['0045ad0c1e14a4d1f4b011c92eb36b8df63d65bc'],- 'fields': 'title,url,citationCount,authors,publicationTypes- ,publicationDate,openAccessPdf', 'limit': 20, 'save_to_file- ': True}, result={'recommendedPapers': [{'paperId': '9cb20- 2a72171dc954f8180b42e08da7ab31e16a1', 'url': 'https://www.se- manticscholar.org/paper/9cb202a72171dc954f8180b42e08da7ab31e- 16a1', 'title': 'Embrace, Don't Avoid: Reimagining Higher- Education with Generative Artificial Intelligence', 'citat- ionCount': 0, 'openAccessPdf': {'url': 'https://heca-anali- tika.com/jeml/article/download/233/157', 'status': 'HYBR- ID'}, 'publicationTypes': ['JournalArticle'], 'publicatio- nDate': '2024-11-28', 'authors': [{'authorId': '165937196- 7', 'name': 'T. R. Noviandy'}, {'authorId': '1657989613',- 'name': 'A. Maulana'}, {'authorId': '146805414', 'name'-================================================================-'''--# Search author information and save the result in a file-usr_msg = """search the authors of author ids of "2281351310"- ,"2281342663","2300302076","2300141520" for me, and please- save the record in a file."""-camel_agent.reset()-response = camel_agent.step(usr_msg)-print(str(response.info['tool_calls'])[:1000])--'''-================================================================-[FunctionCallingRecord(func_name='fetch_author_data', args=-{'ids': ['2281351310', '2281342663', '2300302076', '230014152-0'], 'fields': 'name,url,paperCount,hIndex,papers', 'save_to_-file': True}, result=[{'authorId': '2281351310', 'url': 'ht-tps://www.semanticscholar.org/author/2281351310', 'name': 'Tho-mas K. F. Chiu', 'paperCount': 3, 'hIndex': 1, 'papers': [{'p-aperId': '218b2e3d3418edff705336a6e0c7f2125be7c562', 'title': N-one}, {'paperId': '630642b7040a0c396967e4dab93cf73094fa4f8f-', 'title': None}, {'paperId': '833ff07d2d1be9be7b12e88487d5631-c141a2e95', 'title': None}]}, {'authorId': '2281342663', 'ur-l': 'https://www.semanticscholar.org/author/2281342663', 'nam-e': 'C. Chai', 'paperCount': 6, 'hIndex': 2, 'papers': [{'pape-rId': '0c70ca68c0239895b0d36abf7f11302cdcf01855', 'title': Non-e}, {'paperId': '218b2e3d3418edff705336a6e0c7f2125be7c562', 't-itle': None}, {'paperId': '7ce699e1cfb81cecf298df6be8eaac8f50-2e0fcc', 'title': None}, {'paperId': '4521b51a8465e69d20a3ae4-b770cf164a180f67b', 'ti-================================================================-'''+# ========= 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 SemanticScholarToolkit+from camel.types import ModelPlatformType, ModelType++# Define the model, here in this case we use gpt-4o+model = ModelFactory.create(+ model_platform=ModelPlatformType.DEFAULT,+ model_type=ModelType.DEFAULT,+ model_config_dict=ChatGPTConfig(temperature=0.0).as_dict(),+)+++sys_msg = "You are a helpful assistant"++# Initialize a toolkit+toolkit = SemanticScholarToolkit()+# Get list of tools+tools = toolkit.get_tools()++# Initialize a ChatAgent with your custom tools+camel_agent = ChatAgent(+ system_message=sys_msg,+ model=model,+ tools=tools,+)++# Description of the added tools+usr_msg = "Describe the tools you've added"++response = camel_agent.step(usr_msg)+print(response.msgs[0].content)++'''+================================================================+1. **fetch_paper_data_title**: This tool fetches a single paper+ based on its title. You can specify which fields to include in+ the response, such as the abstract, authors, year, citation+ count, and more.++2. **fetch_paper_data_id**: Similar to the previous tool,+ this one retrieves a single paper but uses a paper ID instead+ of the title. It also allows for specifying the fields to+ include in the response.++3. **fetch_bulk_paper_data**: This tool allows you to fetch+ multiple papers at once based on a query that can include+ various operators (like AND, OR, NOT). You can filter by+ year and specify which fields to return.++4. **fetch_recommended_papers**: This tool provides+ recommendations for papers based on a list of positively+ and negatively correlated paper IDs. You can specify the+ fields to include in the response and limit the number+ of papers returned.++5. **fetch_author_data**: This tool retrieves information+ about authors based on their IDs. You can specify which+ fields to include in the response, such as the author's name,+ URL, paper count, h-index, and their papers.++These tools can be used individually or in combination to+ gather comprehensive information about academic literature+ and authors.+================================================================+'''++# Search a paper through its id+usr_msg = """search the paper 'Construction of the Literature+ Graph in Semantic Scholar' for me including its paperid"""+camel_agent.reset()+response = camel_agent.step(usr_msg)+print(str(response.info['tool_calls'])[:1000])++'''+================================================================+[FunctionCallingRecord(func_name='fetch_paper_data_title',+args={'paperTitle': 'Construction of the Literature Graph in+Semantic Scholar', 'fields': 'title,abstract,authors,year,+citationCount,paperId'}, result={'total': 1, 'offset': 0,+'data': [{'paperId': '649def34f8be52c8b66281af98ae884c09aef38b',+'title': 'Construction of the Literature Graph in Semantic+ Scholar', 'abstract': 'We describe a deployed scalable system+for organizing published scientific literature into a+heterogeneous graph to facilitate algorithmic manipulation and+discovery. The resulting literature graph consists of more than+ 280M nodes, representing papers, authors, entities and various+ interactions between them (e.g., authorships, citations,+ entity mentions). We reduce literature graph construction into+ familiar NLP tasks (e.g., entity extraction and linking),+ point out research challenges due to differences from standard+ formulations of these tasks, and report empirical results for+ each task. The methods describe+================================================================+'''++# Search a paper through its title+usr_msg = """search the paper with paper id of+ '649def34f8be52c8b66281af98ae884c09aef38b' for me"""+camel_agent.reset()+response = camel_agent.step(usr_msg)+print(str(response.info['tool_calls'])[:1000])++'''+================================================================+[FunctionCallingRecord(func_name='fetch_paper_data_id', args=+{'paperID': '649def34f8be52c8b66281af98ae884c09aef38b',+'fields': 'title,abstract,authors,year,citationCount,+publicationTypes,publicationDate,openAccessPdf'},+result={'paperId': '649def34f8be52c8b66281af98ae884c09aef38b',+'title': 'Construction of the Literature Graph in Semantic+ Scholar', 'abstract': 'We describe a deployed scalable system+ for organizing published scientific literature into a+ heterogeneous graph to facilitate algorithmic manipulation+ and discovery. The resulting literature graph consists of+ more than 280M nodes, representing papers, authors, entities+ and various interactions between them (e.g., authorships,+ citations, entity mentions). We reduce literature graph+ construction into familiar NLP tasks (e.g., entity extraction+ and linking), point out research challenges due to differences+ from standard formulations of these tasks, and report+ empirical results for each task. The methods described+ in this paper ar+================================================================+'''++# Search papers through related topic+usr_msg = """search 3 papers with topic related to+ 'generative ai' from 2024 for me"""+camel_agent.reset()+response = camel_agent.step(usr_msg)+print(str(response.info['tool_calls'])[:1000])++'''+================================================================+[FunctionCallingRecord(func_name='fetch_bulk_paper_data',+args={'query': 'generative ai', 'year': '2024-', 'fields':+'title,url,publicationTypes,publicationDate,openAccessPdf'},+result={'total': 9849, 'token': 'PCOA3RZZB2ADADAEYCX2BLJJRDEGL+PUCFA3I5XJAKEAB3YXPGDOTY2GU3WHI4ZMALUMAPUDPHP724CEUVEFKTYRZY5K+LUU53Y5MWWEINIKYZZRC3YT3H4AF7CTSQ', 'data': [{'paperId':+'0008cd09c0449451b9e6e6de35c29009f0883cd9', 'url': 'https://www+.semanticscholar.org/paper/0008cd09c0449451b9e6e6de35c29009+f0883cd9', 'title': 'A Chitchat on Using ChatGPT for Cheating',+ 'openAccessPdf': {'url': 'https://doi.org/10.34074/proc.240106'+ , 'status': 'BRONZE'}, 'publicationTypes': ['Conference'],+ 'publicationDate': '2024-07-24'}, {'paperId': '0013aecf813400+ 174158e4f012918c5408f90962', 'url': 'https://www.semanticsc+ holar.org/paper/0013aecf813400174158e4f012918c5408f90962',+ 'title': 'Can novice teachers detect AI-generated texts in EFL+ writing?', 'openAccessPdf': None, 'publicationTypes':+ ['JournalArticle'], 'publicationDate'+================================================================+'''++# Search papers through related topic and operator+usr_msg = """search 2 papers with topic related to+ 'ai and bio' from 2024 for me"""+camel_agent.reset()+response = camel_agent.step(usr_msg)+print(str(response.info['tool_calls'])[:1000])++'''+================================================================+[FunctionCallingRecord(func_name='fetch_bulk_paper_data',+args={'query': 'ai and bio', 'year': '2024-', 'fields': 'title,+url,publicationTypes,publicationDate,openAccessPdf'}, result=+{'total': 207, 'token': None, 'data': [{'paperId': '00c8477a9c+c28b85e4f6da13d2a889c94a955291', 'url': 'https://www.semantics+cholar.org/paper/00c8477a9cc28b85e4f6da13d2a889c94a955291',+'title': 'Explaining Enterprise Knowledge Graphs with Large+ Language Models and Ontological Reasoning', 'openAccessPdf':+ None, 'publicationTypes': ['JournalArticle'], 'publicationDate+ ': None}, {'paperId': '01726fbfc8ee716c82b9c4cd70696906d3a4+ 46d0', 'url': 'https://www.semanticscholar.org/paper/01726fbfc+ 8ee716c82b9c4cd70696906d3a446d0', 'title': 'Study Research+ Protocol for Phenome India-CSIR Health Cohort Knowledgebase+ (PI-CHeCK): A Prospective multi-modal follow-up study on a+ nationwide employee cohort.', 'openAccessPdf': {'url':+ 'https://www.medrxiv.org/content/medrxiv/early/2024/10/19/2024+ .10.17.24315252.full.pdf', 'status'+================================================================+'''++# Recommend papers through positive and negative paper id+usr_msg = """recommend 2 papers with positive paper id+ of "02138d6d094d1e7511c157f0b1a3dd4e5b20ebee",+ "018f58247a20ec6b3256fd3119f57980a6f37748" and negative+ paper id of "0045ad0c1e14a4d1f4b011c92eb36b8df63d65bc"+ for me"""+camel_agent.reset()+response = camel_agent.step(usr_msg)+print(str(response.info['tool_calls'])[:1000])++'''+================================================================+[FunctionCallingRecord(func_name='fetch_recommended_papers',+args={'positive_paper_ids': ['02138d6d094d1e7511c157f0b1a3dd4e+5b20ebee', '018f58247a20ec6b3256fd3119f57980a6f37748'], 'negati+ve_paper_ids': ['0045ad0c1e14a4d1f4b011c92eb36b8df63d65bc'],+'fields': 'title,url,citationCount,authors,publicationTypes,+publicationDate,openAccessPdf', 'limit': 20, 'save_to_file': F+alse}, result={'recommendedPapers': [{'paperId': '9cb202a72171+dc954f8180b42e08da7ab31e16a1', 'url': 'https://www.semanticsc+holar.org/paper/9cb202a72171dc954f8180b42e08da7ab31e16a1', 'tit+le': 'Embrace, Don't Avoid: Reimagining Higher Education with+ Generative Artificial Intelligence', 'citationCount': 0, 'op+ enAccessPdf': {'url': 'https://heca-analitika.com/jeml/arti+ cle/download/233/157', 'status': 'HYBRID'}, 'publicationT+ ypes': ['JournalArticle'], 'publicationDate': '2024-11-2+ 8', 'authors': [{'authorId': '1659371967', 'name': 'T. R. N+ oviandy'}, {'authorId': '1657989613', 'name': 'A. Maulan+ a'}, {'authorId': '146805414', 'name+================================================================+'''++# Recommend papers and save the result in a file+usr_msg = """search the authors of author ids of "2281351310",+ "2281342663","2300302076","2300141520" for me"""+camel_agent.reset()+response = camel_agent.step(usr_msg)+print(str(response.info['tool_calls'])[:1000])++'''+================================================================+[FunctionCallingRecord(func_name='fetch_recommended_papers',+args={'positive_paper_ids': ['02138d6d094d1e7511c157f0b1a3dd4e5+b20ebee', '018f58247a20ec6b3256fd3119f57980a6f37748'], 'negativ+e_paper_ids': ['0045ad0c1e14a4d1f4b011c92eb36b8df63d65bc'],+ 'fields': 'title,url,citationCount,authors,publicationTypes,+ publicationDate,openAccessPdf', 'limit': 20, 'save_to_file': T+ rue}, result={'recommendedPapers': [{'paperId': '9cb202a7217+ 1dc954f8180b42e08da7ab31e16a1', 'url': 'https://www.semantics+ cholar.org/paper/9cb202a72171dc954f8180b42e08da7ab31e16a1',+ 'title': 'Embrace, Don't Avoid: Reimagining Higher Education+ with Generative Artificial Intelligence', 'citationCount':+ 0, 'openAccessPdf': {'url': 'https://heca-analitika.com/jeml+ /article/download/233/157', 'status': 'HYBRID'}, 'publication+ Types': ['JournalArticle'], 'publicationDate': '2024-11-28',+ 'authors': [{'authorId': '1659371967', 'name': 'T. R. Novia+ ndy'}, {'authorId': '1657989613', 'name': 'A. Maulana'},+ {'authorId': '146805414', 'name'+================================================================+'''++# Search author information through author id+usr_msg = """recommend 2 papers with positive paper id+ of "02138d6d094d1e7511c157f0b1a3dd4e5b20ebee", "018f5+ 8247a20ec6b3256fd3119f57980a6f37748" and negative paper+ id of "0045ad0c1e14a4d1f4b011c92eb36b8df63d65bc" for me,+ and please save the result in a file."""+camel_agent.reset()+response = camel_agent.step(usr_msg)+print(str(response.info['tool_calls'])[:1000])++'''+================================================================+[FunctionCallingRecord(func_name='fetch_recommended_papers',+args={'positive_paper_ids': ['02138d6d094d1e7511c157f0b1a3dd4e5+b20ebee', '018f58247a20ec6b3256fd3119f57980a6f37748'], 'negat+ive_paper_ids': ['0045ad0c1e14a4d1f4b011c92eb36b8df63d65bc'],+ 'fields': 'title,url,citationCount,authors,publicationTypes+ ,publicationDate,openAccessPdf', 'limit': 20, 'save_to_file+ ': True}, result={'recommendedPapers': [{'paperId': '9cb20+ 2a72171dc954f8180b42e08da7ab31e16a1', 'url': 'https://www.se+ manticscholar.org/paper/9cb202a72171dc954f8180b42e08da7ab31e+ 16a1', 'title': 'Embrace, Don't Avoid: Reimagining Higher+ Education with Generative Artificial Intelligence', 'citat+ ionCount': 0, 'openAccessPdf': {'url': 'https://heca-anali+ tika.com/jeml/article/download/233/157', 'status': 'HYBR+ ID'}, 'publicationTypes': ['JournalArticle'], 'publicatio+ nDate': '2024-11-28', 'authors': [{'authorId': '165937196+ 7', 'name': 'T. R. Noviandy'}, {'authorId': '1657989613',+ 'name': 'A. Maulana'}, {'authorId': '146805414', 'name'+================================================================+'''++# Search author information and save the result in a file+usr_msg = """search the authors of author ids of "2281351310"+ ,"2281342663","2300302076","2300141520" for me, and please+ save the record in a file."""+camel_agent.reset()+response = camel_agent.step(usr_msg)+print(str(response.info['tool_calls'])[:1000])++'''+================================================================+[FunctionCallingRecord(func_name='fetch_author_data', args=+{'ids': ['2281351310', '2281342663', '2300302076', '230014152+0'], 'fields': 'name,url,paperCount,hIndex,papers', 'save_to_+file': True}, result=[{'authorId': '2281351310', 'url': 'ht+tps://www.semanticscholar.org/author/2281351310', 'name': 'Tho+mas K. F. Chiu', 'paperCount': 3, 'hIndex': 1, 'papers': [{'p+aperId': '218b2e3d3418edff705336a6e0c7f2125be7c562', 'title': N+one}, {'paperId': '630642b7040a0c396967e4dab93cf73094fa4f8f+', 'title': None}, {'paperId': '833ff07d2d1be9be7b12e88487d5631+c141a2e95', 'title': None}]}, {'authorId': '2281342663', 'ur+l': 'https://www.semanticscholar.org/author/2281342663', 'nam+e': 'C. Chai', 'paperCount': 6, 'hIndex': 2, 'papers': [{'pape+rId': '0c70ca68c0239895b0d36abf7f11302cdcf01855', 'title': Non+e}, {'paperId': '218b2e3d3418edff705336a6e0c7f2125be7c562', 't+itle': None}, {'paperId': '7ce699e1cfb81cecf298df6be8eaac8f50+2e0fcc', 'title': None}, {'paperId': '4521b51a8465e69d20a3ae4+b770cf164a180f67b', 'ti+================================================================+'''diff --git a/pyproject.toml b/pyproject.tomlindex bf7842eac..24a27e37e 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -166,6 +166,7 @@ dev_tools = ["typer>=0.15.2","mcp>=1.3.0","daytona-sdk==0.14.0",+ "aci-sdk>=1.0.0b1",]model_platforms = ["litellm>=1.38.1,<2",@@ -245,6 +246,7 @@ owl = ["crawl4ai>=0.3.745","scrapegraph-py>=1.12.0,<2","pyautogui>=0.9.54,<0.10",+ "aci-sdk>=1.0.0b1",]all = ["numpy~=1.26",@@ -361,6 +363,7 @@ all = ["daytona-sdk==0.14.0","ibm-watsonx-ai>=1.3.11","google-genai>=1.13.0",+ "aci-sdk>=1.0.0b1",][project.urls]@@ -562,4 +565,4 @@ skip = '.git*,*.pdf,*.svg,*.lock,*.css,examples/toolkits/semantic_scholar_toolkicheck-hidden = true# Ignore long lines as usually some kind of base64 encodings e.g. in ipynbignore-regex = '^\s*"image/\S+": ".*|^.{300,}|\b(NotIn|Unsupport)\b'-ignore-words-list = 'ans,datas,rouge,doubleClick,OCE'+ignore-words-list = 'ans,datas,rouge,doubleClick,OCE,ACI,aci'diff --git a/test/toolkits/test_aci_toolkit.py b/test/toolkits/test_aci_toolkit.pynew file mode 100644index 000000000..00acb40b7--- /dev/null+++ b/test/toolkits/test_aci_toolkit.py@@ -0,0 +1,282 @@+# ========= 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 os+import sys+from unittest.mock import MagicMock, patch++import pytest++from camel.toolkits.aci_toolkit import ACIToolkit++# Add aci to sys.modules to allow patching+sys.modules['aci'] = MagicMock()+sys.modules['aci.types'] = MagicMock()+sys.modules['aci.types.enums'] = MagicMock()+++ os.getenv("ACI_API_KEY") is None, reason="ACI_API_KEY not set"+)+def test_aci_toolkit_init():+ r"""Test ACIToolkit initialization."""+ # Test initialization with default parameters+ toolkit = ACIToolkit()+ assert toolkit._api_key == os.getenv("ACI_API_KEY")+ assert toolkit._base_url == os.getenv("ACI_BASE_URL")+ assert toolkit.linked_account_owner_id is None++ # Test initialization with custom parameters+ custom_api_key = "test_api_key"+ custom_base_url = "https://test.api.url"+ custom_owner_id = "test_owner"+ toolkit = ACIToolkit(+ api_key=custom_api_key,+ base_url=custom_base_url,+ linked_account_owner_id=custom_owner_id,+ )+ assert toolkit._api_key == custom_api_key+ assert toolkit._base_url == custom_base_url+ assert toolkit.linked_account_owner_id == custom_owner_id+++@patch("aci.ACI")+def test_search_tool(mock_aci):+ r"""Test search_tool method."""+ # Setup mock+ mock_client = MagicMock()+ mock_aci.return_value = mock_client+ mock_client.apps.search.return_value = ["app1", "app2"]++ # Initialize toolkit and call method+ toolkit = ACIToolkit(api_key="test_key")+ result = toolkit.search_tool(+ intent="test intent",+ allowed_app_only=True,+ include_functions=True,+ categories=["category1"],+ limit=5,+ offset=0,+ )++ # Verify results+ assert result == ["app1", "app2"]+ mock_client.apps.search.assert_called_once_with(+ intent="test intent",+ allowed_apps_only=True,+ include_functions=True,+ categories=["category1"],+ limit=5,+ offset=0,+ )+++@patch("aci.ACI")+def test_search_tool_exception(mock_aci):+ r"""Test search_tool method with exception."""+ # Setup mock to raise exception+ mock_client = MagicMock()+ mock_aci.return_value = mock_client+ mock_client.apps.search.side_effect = Exception("Test error")++ # Initialize toolkit and call method+ toolkit = ACIToolkit(api_key="test_key")+ result = toolkit.search_tool()++ # Verify results+ assert result == "Test error"+ mock_client.apps.search.assert_called_once()+++@patch("aci.ACI")+def test_list_configured_apps(mock_aci):+ r"""Test list_configured_apps method."""+ # Setup mock+ mock_client = MagicMock()+ mock_aci.return_value = mock_client+ mock_client.app_configurations.list.return_value = ["config1", "config2"]++ # Initialize toolkit and call method+ toolkit = ACIToolkit(api_key="test_key")+ result = toolkit.list_configured_apps(+ app_names=["app1"], limit=5, offset=0+ )++ # Verify results+ assert result == ["config1", "config2"]+ mock_client.app_configurations.list.assert_called_once_with(+ app_names=["app1"], limit=5, offset=0+ )+++@patch("aci.types.enums.SecurityScheme")+@patch("aci.ACI")+def test_configure_app(mock_aci, mock_security_scheme):+ r"""Test configure_app method."""+ # Setup mock+ mock_client = MagicMock()+ mock_aci.return_value = mock_client++ # Mock app details with API key security scheme+ mock_app_details = MagicMock()+ mock_app_details.security_schemes = ["api_key"]+ mock_client.apps.get.return_value = mock_app_details++ # Mock SecurityScheme enum+ mock_security_scheme.API_KEY = "api_key"++ mock_client.app_configurations.create.return_value = {"status": "success"}++ # Initialize toolkit and call method+ toolkit = ACIToolkit(api_key="test_key")+ result = toolkit.configure_app(app_name="test_app")++ # Verify results+ assert result == {"status": "success"}+ mock_client.apps.get.assert_called_once_with(app_name="test_app")+ mock_client.app_configurations.create.assert_called_once()+++@patch("aci.ACI")+def test_enable_linked_account(mock_aci):+ r"""Test enable_linked_account method."""+ # Setup mock+ mock_client = MagicMock()+ mock_aci.return_value = mock_client++ mock_linked_account = MagicMock()+ mock_linked_account.id = "test_id"+ mock_linked_account.enabled = True++ mock_client.linked_accounts.enable.return_value = mock_linked_account++ # Initialize toolkit and call method+ toolkit = ACIToolkit(api_key="test_key")+ result = toolkit.enable_linked_account(linked_account_id="test_id")++ # Verify results+ assert result == mock_linked_account+ assert result.enabled is True+ mock_client.linked_accounts.enable.assert_called_once_with(+ linked_account_id="test_id"+ )+++@patch("aci.ACI")+def test_disable_linked_account(mock_aci):+ r"""Test disable_linked_account method."""+ # Setup mock+ mock_client = MagicMock()+ mock_aci.return_value = mock_client++ mock_linked_account = MagicMock()+ mock_linked_account.id = "test_id"+ mock_linked_account.enabled = False++ mock_client.linked_accounts.disable.return_value = mock_linked_account++ # Initialize toolkit and call method+ toolkit = ACIToolkit(api_key="test_key")+ result = toolkit.disable_linked_account(linked_account_id="test_id")++ # Verify results+ assert result == mock_linked_account+ assert result.enabled is False+ mock_client.linked_accounts.disable.assert_called_once_with(+ linked_account_id="test_id"+ )+++@patch("aci.ACI")+def test_delete_linked_account(mock_aci):+ r"""Test delete_linked_account method."""+ # Setup mock+ mock_client = MagicMock()+ mock_aci.return_value = mock_client++ # Initialize toolkit and call method+ toolkit = ACIToolkit(api_key="test_key")+ result = toolkit.delete_linked_account(linked_account_id="test_id")++ # Verify results+ assert "test_id" in result+ assert "deleted successfully" in result+ mock_client.linked_accounts.delete.assert_called_once_with(+ linked_account_id="test_id"+ )+++@patch("aci.ACI")+def test_get_tools(mock_aci):+ r"""Test get_tools method."""+ # Setup mock+ mock_client = MagicMock()+ mock_aci.return_value = mock_client++ # Mock configured apps+ mock_app = MagicMock()+ mock_app.app_name = "test_app"+ mock_client.app_configurations.list.return_value = [mock_app]++ # Mock function search+ mock_client.functions.search.return_value = [+ {"function": {"name": "test_function"}}+ ]++ # Mock function definition+ mock_client.functions.get_definition.return_value = {+ "type": "function",+ "function": {+ "name": "test_function",+ "description": "Test function",+ "parameters": {"type": "object", "properties": {}, "required": []},+ },+ }++ # Initialize toolkit and call method+ toolkit = ACIToolkit(api_key="test_key")+ result = toolkit.get_tools()++ # Verify results+ assert len(result) == 1+ assert result[0].get_function_name() == "test_function"+ mock_client.app_configurations.list.assert_called_once()+ mock_client.functions.search.assert_called_once()+ mock_client.functions.get_definition.assert_called_once_with(+ "test_function"+ )+++@patch("aci.ACI")+def test_execute_function(mock_aci):+ r"""Test execute_function method."""+ # Setup mock+ mock_client = MagicMock()+ mock_aci.return_value = mock_client+ mock_client.handle_function_call.return_value = {"result": "success"}++ # Initialize toolkit and call method+ toolkit = ACIToolkit(api_key="test_key")+ result = toolkit.execute_function(+ function_name="test_function",+ function_arguments={"arg1": "value1"},+ linked_account_owner_id="test_owner",+ allowed_apps_only=True,+ )++ # Verify results+ assert result == {"result": "success"}+ mock_client.handle_function_call.assert_called_once_with(+ "test_function", {"arg1": "value1"}, "test_owner", True+ )diff --git a/uv.lock b/uv.lockindex 79a153ffa..7116c275d 100644--- a/uv.lock+++ b/uv.lock@@ -43,6 +43,22 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/8d/3f/95338030883d8c8b91223b4e21744b04d11b161a3ef117295d8241f50ab4/accessible_pygments-0.0.5-py3-none-any.whl", hash = "sha256:88ae3211e68a1d0b011504b2ffc1691feafce124b845bd072ab6f9f66f34d4b7", size = 1395903 },]+[[package]]+name = "aci-sdk"+version = "1.0.0b1"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "griffe" },+ { name = "httpx" },+ { name = "pydantic" },+ { name = "tenacity" },+ { name = "typing-extensions" },+]+sdist = { url = "https://files.pythonhosted.org/packages/71/9d/0d956545331ac6760af30a7bc6492083a84b32f16faa89f28ee269a83dac/aci_sdk-1.0.0b1.tar.gz", hash = "sha256:9130bf196c680deda2004d71b091883bc468ea1649d71dbf676b9172c067d4ef", size = 63449 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/e2/57/2f1cfb3ee6a84e355a09dd94a4c3c5d1dbe9dbb925950c6903cb8ef2a216/aci_sdk-1.0.0b1-py3-none-any.whl", hash = "sha256:f3d9f3de58c518ecf4fc44ebedf1e4a1e23a30df268782989d1ce8852bd47175", size = 31713 },+]+[[package]]name = "agentops"version = "0.3.26"@@ -556,6 +572,7 @@ dependencies = [[package.optional-dependencies]all = [{ name = "accelerate" },+ { name = "aci-sdk" },{ name = "agentops" },{ name = "aiosqlite" },{ name = "anthropic" },@@ -710,6 +727,7 @@ dev = [{ name = "uv" },]dev-tools = [+ { name = "aci-sdk" },{ name = "agentops" },{ name = "daytona-sdk" },{ name = "docker" },@@ -773,6 +791,7 @@ model-platforms = [{ name = "reka-api" },]owl = [+ { name = "aci-sdk" },{ name = "anthropic" },{ name = "beautifulsoup4" },{ name = "chunkr-ai" },@@ -887,6 +906,9 @@ web-tools = [requires-dist = [{ name = "accelerate", marker = "extra == 'all'", specifier = ">=0.26.0,<0.27" },{ name = "accelerate", marker = "extra == 'huggingface'", specifier = ">=0.26.0,<0.27" },+ { name = "aci-sdk", marker = "extra == 'all'", specifier = ">=1.0.0b1" },+ { name = "aci-sdk", marker = "extra == 'dev-tools'", specifier = ">=1.0.0b1" },+ { name = "aci-sdk", marker = "extra == 'owl'", specifier = ">=1.0.0b1" },{ name = "agentops", marker = "extra == 'all'", specifier = ">=0.3.21,<0.4" },{ name = "agentops", marker = "extra == 'dev-tools'", specifier = ">=0.3.21,<0.4" },{ name = "aiosqlite", marker = "extra == 'all'", specifier = ">=0.20.0,<0.21" },@@ -2597,6 +2619,18 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/8a/d4/70d262492338c4939f97dca310c45b002a3af84b265720f0e9b135bc85b2/greenlet-3.2.0-cp312-cp312-win_amd64.whl", hash = "sha256:211a9721f540e454a02e62db7956263e9a28a6cf776d4b9a7213844e36426333", size = 296217 },]+[[package]]+name = "griffe"+version = "1.7.3"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "colorama" },+]+sdist = { url = "https://files.pythonhosted.org/packages/a9/3e/5aa9a61f7c3c47b0b52a1d930302992229d191bf4bc76447b324b731510a/griffe-1.7.3.tar.gz", hash = "sha256:52ee893c6a3a968b639ace8015bec9d36594961e156e23315c8e8e51401fa50b", size = 395137 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/58/c6/5c20af38c2a57c15d87f7f38bee77d63c1d2a3689f74fefaf35915dd12b2/griffe-1.7.3-py3-none-any.whl", hash = "sha256:c6b3ee30c2f0f17f30bcdef5068d6ab7a2a4f1b8bf1a3e74b56fffd21e1c5f75", size = 129303 },+]+[[package]]name = "grpcio"version = "1.67.1"@@ -6953,6 +6987,15 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/2f/dd/63d1d2fddcaaee040745ea58d13b54c0b1483260ddae52eb59abf691f757/tavily_python-0.5.4-py3-none-any.whl", hash = "sha256:47f8c0b41283d44849fe9531596cd26d3de42a59618ef66f9e1244d8fedba404", size = 44419 },]+[[package]]+name = "tenacity"+version = "9.1.2"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/0a/d4/2b0cd0fe285e14b36db076e78c93766ff1d529d70408bd1d2a5a84f1d929/tenacity-9.1.2.tar.gz", hash = "sha256:1169d376c297e7de388d18b4481760d478b0e99a777cad3a9c86e556f4b697cb", size = 48036 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/e5/30/643397144bfbfec6f6ef821f36f33e57d35946c44a2352d3c9f0ae847619/tenacity-9.1.2-py3-none-any.whl", hash = "sha256:f77bf36710d8b73a50b2dd155c97b870017ad21afe6ab300326b0371b3b05138", size = 28248 },+]+[[package]]name = "termcolor"version = "2.4.0"