🐫 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: integrate linkedin toolkit (#839)
Neil Johnson3226026c7818
diff --git a/camel/toolkits/__init__.py b/camel/toolkits/__init__.pyindex 72432a7f6..84ae73af5 100644--- a/camel/toolkits/__init__.py+++ b/camel/toolkits/__init__.py@@ -28,6 +28,7 @@ from .twitter_toolkit import TWITTER_FUNCS, TwitterToolkitfrom .weather_toolkit import WEATHER_FUNCS, WeatherToolkitfrom .slack_toolkit import SLACK_FUNCS, SlackToolkitfrom .dalle_toolkit import DALLE_FUNCS, DalleToolkit+from .linkedin_toolkit import LINKEDIN_FUNCS, LinkedInToolkitfrom .base import BaseToolkitfrom .code_execution import CodeExecutionToolkit@@ -47,6 +48,7 @@ __all__ = ['WEATHER_FUNCS','SLACK_FUNCS','DALLE_FUNCS',+ 'LINKEDIN_FUNCS','BaseToolkit','GithubToolkit','MathToolkit',@@ -58,5 +60,6 @@ __all__ = ['WeatherToolkit','RetrievalToolkit','OpenAPIToolkit',+ 'LinkedInToolkit','CodeExecutionToolkit',]diff --git a/camel/toolkits/linkedin_toolkit.py b/camel/toolkits/linkedin_toolkit.pynew file mode 100644index 000000000..46af18a68--- /dev/null+++ b/camel/toolkits/linkedin_toolkit.py@@ -0,0 +1,230 @@+# =========== 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 json+import os+from http import HTTPStatus+from typing import List++import requests++from camel.toolkits import OpenAIFunction+from camel.toolkits.base import BaseToolkit+from camel.utils import handle_http_error++LINKEDIN_POST_LIMIT = 1300+++class LinkedInToolkit(BaseToolkit):+ r"""A class representing a toolkit for LinkedIn operations.++ This class provides methods for creating a post, deleting a post, and+ retrieving the authenticated user's profile information.+ """++ def __init__(self):+ self._access_token = self._get_access_token()++ def create_post(self, text: str) -> dict:+ r"""Creates a post on LinkedIn for the authenticated user.++ Args:+ text (str): The content of the post to be created.++ Returns:+ dict: A dictionary containing the post ID and the content of+ the post. If the post creation fails, the values will be None.++ Raises:+ Exception: If the post creation fails due to+ an error response from LinkedIn API.+ """+ url = 'https://api.linkedin.com/v2/ugcPosts'+ urn = self.get_profile(include_id=True)++ headers = {+ 'X-Restli-Protocol-Version': '2.0.0',+ 'Content-Type': 'application/json',+ 'Authorization': f'Bearer {self._access_token}',+ }++ post_data = {+ "author": urn['id'],+ "lifecycleState": "PUBLISHED",+ "specificContent": {+ "com.linkedin.ugc.ShareContent": {+ "shareCommentary": {"text": text},+ "shareMediaCategory": "NONE",+ }+ },+ "visibility": {+ "com.linkedin.ugc.MemberNetworkVisibility": "PUBLIC"+ },+ }++ response = requests.post(+ url, headers=headers, data=json.dumps(post_data)+ )+ if response.status_code == 201:+ post_response = response.json()+ post_id = post_response.get('id', None) # Get the ID of the post+ return {'Post ID': post_id, 'Text': text}+ else:+ raise Exception(+ f"Failed to create post. Status code: {response.status_code}, "+ f"Response: {response.text}"+ )++ def delete_post(self, post_id: str) -> str:+ r"""Deletes a LinkedIn post with the specified ID+ for an authorized user.++ This function sends a DELETE request to the LinkedIn API to delete+ a post with the specified ID. Before sending the request, it+ prompts the user to confirm the deletion.++ Args:+ post_id (str): The ID of the post to delete.++ Returns:+ str: A message indicating the result of the deletion. If the+ deletion was successful, the message includes the ID of the+ deleted post. If the deletion was not successful, the message+ includes an error message.++ Reference:+ https://docs.microsoft.com/en-us/linkedin/marketing/integrations/community-management/shares/ugc-post-api+ """+ print(+ "You are going to delete a LinkedIn post "+ f"with the following ID: {post_id}"+ )++ confirm = input(+ "Are you sure you want to delete this post? (yes/no): "+ )+ if confirm.lower() != "yes":+ return "Execution cancelled by the user."++ headers = {+ "Authorization": f"Bearer {self._access_token}",+ "Content-Type": "application/json",+ }++ response = requests.delete(+ f"https://api.linkedin.com/v2/ugcPosts/{post_id}",+ headers=headers,+ )++ if response.status_code != HTTPStatus.NO_CONTENT:+ error_type = handle_http_error(response)+ return (+ f"Request returned a(n) {error_type!s}: "+ f"{response.status_code!s} {response.text}"+ )++ return f"Post deleted successfully. Post ID: {post_id}."++ def get_profile(self, include_id: bool = False) -> dict:+ r"""Retrieves the authenticated user's LinkedIn profile info.++ This function sends a GET request to the LinkedIn API to retrieve the+ authenticated user's profile information. Optionally, it also returns+ the user's LinkedIn ID.++ Args:+ include_id (bool): Whether to include the LinkedIn profile ID in+ the response.++ Returns:+ dict: A dictionary containing the user's LinkedIn profile+ information. If `include_id` is True, the dictionary will also+ include the profile ID.++ Raises:+ Exception: If the profile retrieval fails due to an error response+ from LinkedIn API.+ """+ headers = {+ "Authorization": f"Bearer {self._access_token}",+ 'Connection': 'Keep-Alive',+ 'Content-Type': 'application/json',+ "X-Restli-Protocol-Version": "2.0.0",+ }++ response = requests.get(+ "https://api.linkedin.com/v2/userinfo",+ headers=headers,+ )++ if response.status_code != HTTPStatus.OK:+ raise Exception(+ f"Failed to retrieve profile. "+ f"Status code: {response.status_code}, "+ f"Response: {response.text}"+ )++ json_response = response.json()++ locale = json_response.get('locale', {})+ country = locale.get('country', 'N/A')+ language = locale.get('language', 'N/A')++ profile_report = {+ "Country": country,+ "Language": language,+ "First Name": json_response.get('given_name'),+ "Last Name": json_response.get('family_name'),+ "Email": json_response.get('email'),+ }++ if include_id:+ profile_report['id'] = f"urn:li:person:{json_response['sub']}"++ return profile_report++ def get_tools(self) -> List[OpenAIFunction]:+ r"""Returns a list of OpenAIFunction objects representing the+ functions in the toolkit.++ Returns:+ List[OpenAIFunction]: A list of OpenAIFunction objects+ representing the functions in the toolkit.+ """+ return [+ OpenAIFunction(self.create_post),+ OpenAIFunction(self.delete_post),+ OpenAIFunction(self.get_profile),+ ]++ def _get_access_token(self) -> str:+ r"""Fetches the access token required for making LinkedIn API requests.++ Returns:+ str: The OAuth 2.0 access token or warming message if the+ environment variable `LINKEDIN_ACCESS_TOKEN` is not set or is+ empty.++ Reference:+ You can apply for your personal LinkedIn API access token through+ the link below:+ https://www.linkedin.com/developers/apps+ """+ token = os.getenv("LINKEDIN_ACCESS_TOKEN")+ if not token:+ return "Access token not found. Please set LINKEDIN_ACCESS_TOKEN."+ return token+++LINKEDIN_FUNCS: List[OpenAIFunction] = LinkedInToolkit().get_tools()diff --git a/camel/utils/__init__.py b/camel/utils/__init__.pyindex 5b75e5492..97a5f4940 100644--- a/camel/utils/__init__.py+++ b/camel/utils/__init__.py@@ -27,6 +27,7 @@ from .commons import (get_pydantic_object_schema,get_system_information,get_task_list,+ handle_http_error,is_docker_running,json_to_function_code,print_text_animated,@@ -76,4 +77,5 @@ __all__ = ['agentops_decorator','AgentOpsMeta','track_agent',+ 'handle_http_error',]diff --git a/camel/utils/commons.py b/camel/utils/commons.pyindex 1b6359e06..727e0d77e 100644--- a/camel/utils/commons.py+++ b/camel/utils/commons.py@@ -20,6 +20,7 @@ import subprocessimport timeimport zipfilefrom functools import wraps+from http import HTTPStatusfrom typing import (Any,Callable,@@ -547,3 +548,24 @@ def track_agent(*args, **kwargs):return freturn noop+++def handle_http_error(response: requests.Response) -> str:+ r"""Handles the HTTP errors based on the status code of the response.++ Args:+ response (requests.Response): The HTTP response from the API call.++ Returns:+ str: The error type, based on the status code.+ """+ if response.status_code == HTTPStatus.UNAUTHORIZED:+ return "Unauthorized. Check your access token."+ elif response.status_code == HTTPStatus.FORBIDDEN:+ return "Forbidden. You do not have permission to perform this action."+ elif response.status_code == HTTPStatus.NOT_FOUND:+ return "Not Found. The resource could not be located."+ elif response.status_code == HTTPStatus.TOO_MANY_REQUESTS:+ return "Too Many Requests. You have hit the rate limit."+ else:+ return "HTTP Error"diff --git a/test/toolkits/test_linkedin_function.py b/test/toolkits/test_linkedin_function.pynew file mode 100644index 000000000..db97a0160--- /dev/null+++ b/test/toolkits/test_linkedin_function.py@@ -0,0 +1,115 @@+# =========== 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 http import HTTPStatus+from unittest.mock import MagicMock, patch++import pytest++from camel.toolkits import LinkedInToolkit+++def linkedin_toolkit(monkeypatch):+ # Mock _get_access_token method to return a fake token+ monkeypatch.setattr(+ LinkedInToolkit, "_get_access_token", lambda self: "fake_token"+ )+ return LinkedInToolkit()+++def test_create_post(monkeypatch, linkedin_toolkit):+ # Mock the profile response including the ID+ mock_profile = {'id': 'urn:li:person:test-id'}+ monkeypatch.setattr(+ linkedin_toolkit, 'get_profile', lambda include_id: mock_profile+ )++ # Create a mock response object for post creation+ mock_response = MagicMock()+ mock_response.json.return_value = {+ 'id': 'urn:li:share:7234172587444953088'+ }+ mock_response.status_code = 201++ # Mock the post request+ with patch('requests.post') as mock_post:+ mock_post.return_value = mock_response++ # Call the create_post function+ response = linkedin_toolkit.create_post(+ text="A post created by LinkedInToolkit @Camel."+ )++ # Verify the output+ expected_response = {+ 'Post ID': 'urn:li:share:7234172587444953088',+ 'Text': 'A post created by LinkedInToolkit @Camel.',+ }+ assert response == expected_response+++def test_delete_post(monkeypatch, linkedin_toolkit):+ # Mock the delete response+ mock_response = MagicMock()+ mock_response.status_code = HTTPStatus.NO_CONTENT++ # Mock the input function to simulate user confirmation+ monkeypatch.setattr('builtins.input', lambda _: 'yes')++ # Mock the delete request+ with patch('requests.delete') as mock_delete:+ mock_delete.return_value = mock_response++ # Call the delete_post function+ response = linkedin_toolkit.delete_post(+ post_id="urn:li:share:7234172587444953088"+ )++ # Verify the output+ expected_response = (+ "Post deleted successfully. Post ID: "+ "urn:li:share:7234172587444953088."+ )+ assert response == expected_response+++def test_get_profile(linkedin_toolkit):+ # Mock the profile response+ mock_response = MagicMock()+ mock_response.json.return_value = {+ 'locale': {'country': 'US', 'language': 'en'},+ 'given_name': 'Neil',+ 'family_name': 'John',+ 'email': '[email protected]',+ 'sub': 'test-id',+ }+ mock_response.status_code = HTTPStatus.OK++ # Mock the get request+ with patch('requests.get') as mock_get:+ mock_get.return_value = mock_response++ # Call the get_profile function with include_id=True+ response = linkedin_toolkit.get_profile(include_id=True)++ # Verify the output+ expected_report = {+ 'Country': 'US',+ 'Language': 'en',+ 'First Name': 'Neil',+ 'Last Name': 'John',+ 'Email': '[email protected]',+ 'id': 'urn:li:person:test-id',+ }+ assert response == expected_report