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: Integrate Zapier AI tool (#1594)

Asher-hss7821e6e1fa65
diff --git a/camel/toolkits/__init__.py b/camel/toolkits/__init__.py
index 27cd2c8b1..475f3aaa5 100644
--- a/camel/toolkits/__init__.py
+++ b/camel/toolkits/__init__.py
@@ -47,6 +47,7 @@ from .video_toolkit import VideoDownloaderToolkit
from .dappier_toolkit import DappierToolkit
from .networkx_toolkit import NetworkXToolkit
from .semantic_scholar_toolkit import SemanticScholarToolkit
+from .zapier_toolkit import ZapierToolkit
from .sympy_toolkit import SymPyToolkit
from .mineru_toolkit import MinerUToolkit
@@ -84,6 +85,7 @@ __all__ = [
'DappierToolkit',
'NetworkXToolkit',
'SemanticScholarToolkit',
+ 'ZapierToolkit',
'SymPyToolkit',
'MinerUToolkit',
]
diff --git a/camel/toolkits/zapier_toolkit.py b/camel/toolkits/zapier_toolkit.py
new file mode 100644
index 000000000..08b623c07
--- /dev/null
+++ b/camel/toolkits/zapier_toolkit.py
@@ -0,0 +1,191 @@
+# ========= 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 Any, Dict, List
+
+import requests
+
+from camel.toolkits.base import BaseToolkit
+from camel.toolkits.function_tool import FunctionTool
+from camel.utils import api_keys_required, dependencies_required
+
+
+class ZapierToolkit(BaseToolkit):
+ r"""A class representing a toolkit for interacting with Zapier's NLA API.
+
+ This class provides methods for executing Zapier actions through natural
+ language commands, allowing integration with various web services and
+ automation of workflows through the Zapier platform.
+
+ Attributes:
+ api_key (str): The API key for authenticating with Zapier's API.
+ base_url (str): The base URL for Zapier's API endpoints.
+ """
+
+ @dependencies_required("requests")
+ @api_keys_required(
+ [
+ (None, "ZAPIER_NLA_API_KEY"),
+ ]
+ )
+ def __init__(self) -> None:
+ r"""Initialize the ZapierToolkit with API client. The API key is
+ retrieved from environment variables.
+ """
+ self.api_key = os.environ.get("ZAPIER_NLA_API_KEY")
+ self.base_url = "https://actions.zapier.com/api/v1/"
+
+ def list_actions(self) -> Dict[str, Any]:
+ r"""List all available Zapier actions.
+
+ Returns:
+ Dict[str, Any]: A dictionary containing the list of available
+ actions.
+ """
+ headers = {
+ 'accept': 'application/json',
+ 'x-api-key': self.api_key,
+ }
+ response = requests.get(
+ f"{self.base_url}exposed/",
+ params={'api_key': self.api_key},
+ headers=headers,
+ )
+ response.raise_for_status()
+ return response.json()
+
+ def execute_action(
+ self,
+ action_id: str,
+ instructions: str,
+ ) -> Dict[str, Any]:
+ r"""Execute a specific Zapier action using natural language
+ instructions.
+
+ Args:
+ action_id (str): The ID of the Zapier action to execute.
+ instructions (str): Natural language instructions for executing
+ the action. For example: "Send an email to [email protected]
+ with subject 'Hello' and body 'How are you?'"
+
+ Returns:
+ Dict[str, Any]: The result of the action execution, including
+ status and any output data.
+ """
+ try:
+ headers = {
+ 'accept': 'application/json',
+ 'x-api-key': self.api_key,
+ 'Content-Type': 'application/json',
+ }
+ data = {
+ "instructions": instructions,
+ "preview_only": False,
+ }
+ response = requests.post(
+ f"{self.base_url}exposed/{action_id}/execute/",
+ params={'api_key': self.api_key},
+ headers=headers,
+ json=data,
+ )
+ response.raise_for_status()
+ return response.json()
+ except requests.exceptions.RequestException as e:
+ return {"error": f"Request failed: {e!s}"}
+ except ValueError:
+ return {"error": "Response is not valid JSON"}
+
+ def preview_action(
+ self,
+ action_id: str,
+ instructions: str,
+ ) -> Dict[str, Any]:
+ r"""Preview a specific Zapier action using natural language
+ instructions.
+
+ Args:
+ action_id (str): The ID of the Zapier action to preview.
+ instructions (str): Natural language instructions for previewing
+ the action. For example: "Send an email to [email protected]
+ with subject 'Hello' and body 'How are you?'"
+
+ Returns:
+ Dict[str, Any]: The preview result showing what parameters would
+ be used if the action were executed.
+ """
+ try:
+ headers = {
+ 'accept': 'application/json',
+ 'x-api-key': self.api_key,
+ 'Content-Type': 'application/json',
+ }
+ data = {
+ "instructions": instructions,
+ "preview_only": True,
+ }
+ response = requests.post(
+ f"{self.base_url}exposed/{action_id}/execute/",
+ params={'api_key': self.api_key},
+ headers=headers,
+ json=data,
+ )
+ response.raise_for_status()
+ return response.json()
+ except requests.exceptions.RequestException as e:
+ return {"error": f"Request failed: {e!s}"}
+ except ValueError:
+ return {"error": "Response is not valid JSON"}
+
+ def get_execution_result(self, execution_id: str) -> Dict[str, Any]:
+ r"""Get the execution result of a Zapier action.
+
+ Args:
+ execution_id (str): The execution ID returned from execute_action.
+
+ Returns:
+ Dict[str, Any]: The execution result containing status, logs,
+ and any output data from the action execution.
+ """
+ try:
+ headers = {
+ 'accept': 'application/json',
+ 'x-api-key': self.api_key,
+ }
+ response = requests.get(
+ f"{self.base_url}execution-log/{execution_id}/",
+ params={'api_key': self.api_key},
+ headers=headers,
+ )
+ response.raise_for_status()
+ return response.json()
+ except requests.exceptions.RequestException as e:
+ return {"error": f"Request failed: {e!s}"}
+ except ValueError:
+ return {"error": "Response is not valid JSON"}
+
+ def get_tools(self) -> List[FunctionTool]:
+ r"""Returns a list of FunctionTool objects representing the functions
+ in the toolkit.
+
+ Returns:
+ List[FunctionTool]: A list of FunctionTool objects representing
+ the functions in the toolkit.
+ """
+ return [
+ FunctionTool(self.list_actions),
+ FunctionTool(self.execute_action),
+ FunctionTool(self.preview_action),
+ FunctionTool(self.get_execution_result),
+ ]
diff --git a/examples/toolkits/zapier_toolkit.py b/examples/toolkits/zapier_toolkit.py
new file mode 100644
index 000000000..635c673ce
--- /dev/null
+++ b/examples/toolkits/zapier_toolkit.py
@@ -0,0 +1,101 @@
+# ========= 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.openai_config import ChatGPTConfig
+from camel.models import ModelFactory
+from camel.toolkits import ZapierToolkit
+from camel.types import ModelPlatformType, ModelType
+
+# Define system message
+sys_msg = """You are a helpful AI assistant that can use Zapier AI tools to
+perform various tasks. When using tools, first list the available tools using
+list_actions, then use the appropriate tool based on the task. Always provide
+clear explanations of what you're doing."""
+
+# Set model config
+tools = ZapierToolkit().get_tools()
+model_config_dict = ChatGPTConfig(
+ temperature=0.0,
+).as_dict()
+
+
+model = ModelFactory.create(
+ model_platform=ModelPlatformType.DEFAULT,
+ model_type=ModelType.DEFAULT,
+ model_config_dict=model_config_dict,
+)
+
+# Set agent
+camel_agent = ChatAgent(
+ system_message=sys_msg,
+ model=model,
+ tools=tools,
+)
+camel_agent.reset()
+
+# First, list available tools
+usr_msg = "First, list all available Zapier tools."
+response = camel_agent.step(usr_msg)
+print("Available Tools:")
+print(response.msg.content)
+print("\n" + "=" * 80 + "\n")
+
+# Now, use the translation tool
+usr_msg = """Now that we can see the translation tool is available, please
+use it to translate 'hello camel' from en to zh. Use
+the tool ID from the list above and make sure to specify the language codes
+correctly in the instructions."""
+response = camel_agent.step(usr_msg)
+print("Translation Result:")
+print(response.msg.content)
+
+"""
+===============================================================================
+Here are the available Zapier tools:
+
+1. **Gmail: Find Email**
+ - **ID:** 0d82cfd3-2bd7-4e08-9f3d-692719e81a26
+ - **Description:** This action allows you to find an email in Gmail based
+ on a search string.
+ - **Parameters:**
+ - `instructions`: Instructions for executing the action.
+ - `Search_String`: The string to search for in the emails.
+
+2. **Translate by Zapier: Translate Text**
+ - **ID:** f7527450-d7c7-401f-a764-2f69f622e7f3
+ - **Description:** This action translates text into a specified target
+ language.
+ - **Parameters:**
+ - `instructions`: Instructions for executing the action.
+ - `Text`: The text to be translated.
+ - `Target_Language`: The language to translate the text into.
+
+If you need to perform a specific task using one of these tools, please let me
+know!
+
+================================================================================
+
+Translation Result:
+The translation of "hello camel" from English to Chinese (zh) is:
+
+**Translation:** 你好骆驼
+
+- **Source Language:** English (en)
+- **Target Language:** Chinese (zh)
+
+If you need any further assistance or additional translations, feel free to
+ask!
+===============================================================================
+"""
diff --git a/test/toolkits/test_zapier_ai_function.py b/test/toolkits/test_zapier_ai_function.py
new file mode 100644
index 000000000..43c5f99de
--- /dev/null
+++ b/test/toolkits/test_zapier_ai_function.py
@@ -0,0 +1,97 @@
+# ========= 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 unittest.mock import MagicMock, patch
+
+import pytest
+
+from camel.toolkits import ZapierToolkit
+from camel.toolkits.function_tool import FunctionTool
+
+
+def zapier_toolkit():
+ # Set environment variables for testing
+ os.environ['ZAPIER_NLA_API_KEY'] = 'test_api_key'
+ return ZapierToolkit()
+
+
+def test_init_missing_credentials():
+ # Test initialization with missing credentials
+ os.environ.pop('ZAPIER_NLA_API_KEY', None)
+
+ with pytest.raises(ValueError):
+ ZapierToolkit()
+
+
+@patch('requests.get')
+def test_list_actions_success(mock_get, zapier_toolkit):
+ # Mock successful API response
+ mock_response = MagicMock()
+ mock_response.json.return_value = {
+ "results": [
+ {
+ "id": "action1",
+ "description": "Test action 1",
+ "params": {"param1": "value1"},
+ }
+ ]
+ }
+ mock_response.raise_for_status.return_value = None
+ mock_get.return_value = mock_response
+
+ result = zapier_toolkit.list_actions()
+
+ assert result == mock_response.json.return_value
+ mock_get.assert_called_once_with(
+ f"{zapier_toolkit.base_url}exposed/",
+ params={'api_key': 'test_api_key'},
+ headers={'accept': 'application/json', 'x-api-key': 'test_api_key'},
+ )
+
+
+@patch('requests.post')
+def test_execute_action_success(mock_post, zapier_toolkit):
+ # Mock successful API response
+ mock_response = MagicMock()
+ mock_response.json.return_value = {
+ "result": "Action executed successfully"
+ }
+ mock_response.raise_for_status.return_value = None
+ mock_post.return_value = mock_response
+
+ action_id = "test_action"
+ instructions = "Send an email"
+ result = zapier_toolkit.execute_action(action_id, instructions)
+
+ assert result == mock_response.json.return_value
+ mock_post.assert_called_once_with(
+ f"{zapier_toolkit.base_url}exposed/{action_id}/execute/",
+ params={'api_key': 'test_api_key'},
+ headers={
+ 'accept': 'application/json',
+ 'x-api-key': 'test_api_key',
+ 'Content-Type': 'application/json',
+ },
+ json={'instructions': instructions, 'preview_only': False},
+ )
+
+
+def test_get_tools(zapier_toolkit):
+ # Test get_tools method returns list of FunctionTool objects
+ tools = zapier_toolkit.get_tools()
+ assert isinstance(tools, list)
+ assert len(tools) > 0
+ for tool in tools:
+ assert isinstance(tool, FunctionTool)