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

refactor: twitter toolkit (#1087)

Isaac Jin5a097d6f4614
diff --git a/camel/toolkits/__init__.py b/camel/toolkits/__init__.py
index d1658959c..28ecd5d73 100644
--- a/camel/toolkits/__init__.py
+++ b/camel/toolkits/__init__.py
@@ -36,7 +36,7 @@ from .github_toolkit import GithubToolkit
from .google_scholar_toolkit import GoogleScholarToolkit
from .arxiv_toolkit import ArxivToolkit
from .slack_toolkit import SlackToolkit
-from .twitter_toolkit import TwitterToolkit
+from .twitter_toolkit import TwitterToolkit, TWITTER_FUNCS
from .open_api_toolkit import OpenAPIToolkit
from .retrieval_toolkit import RetrievalToolkit
@@ -68,4 +68,5 @@ __all__ = [
'SEARCH_FUNCS',
'WEATHER_FUNCS',
'DALLE_FUNCS',
+ 'TWITTER_FUNCS',
]
diff --git a/camel/toolkits/twitter_toolkit.py b/camel/toolkits/twitter_toolkit.py
index 9effa833a..bd63446e5 100644
--- a/camel/toolkits/twitter_toolkit.py
+++ b/camel/toolkits/twitter_toolkit.py
@@ -15,505 +15,431 @@ import datetime
import os
from http import HTTPStatus
from http.client import responses
-from typing import List, Optional, Tuple, Union
+from typing import Any, Dict, List, Optional, Union
import requests
+from requests_oauthlib import OAuth1
from camel.toolkits import FunctionTool
from camel.toolkits.base import BaseToolkit
+from camel.utils import api_keys_required
TWEET_TEXT_LIMIT = 280
-class TwitterToolkit(BaseToolkit):
- r"""A class representing a toolkit for Twitter operations.
-
- This class provides methods for creating a tweet, deleting a tweet, and
- getting the authenticated user's profile information.
+@api_keys_required(
+ "TWITTER_CONSUMER_KEY",
+ "TWITTER_CONSUMER_SECRET",
+ "TWITTER_ACCESS_TOKEN",
+ "TWITTER_ACCESS_TOKEN_SECRET",
+)
+def create_tweet(
+ text: str,
+ poll_options: Optional[List[str]] = None,
+ poll_duration_minutes: Optional[int] = None,
+ quote_tweet_id: Optional[Union[int, str]] = None,
+) -> str:
+ r"""Creates a new tweet, optionally including a poll or a quote tweet,
+ or simply a text-only tweet.
+
+ This function sends a POST request to the Twitter API to create a new
+ tweet. The tweet can be a text-only tweet, or optionally include a poll
+ or be a quote tweet. A confirmation prompt is presented to the user
+ before the tweet is created.
+
+ Args:
+ text (str): The text of the tweet. The Twitter character limit for
+ a single tweet is 280 characters.
+ poll_options (Optional[List[str]]): A list of poll options for a
+ tweet with a poll.
+ poll_duration_minutes (Optional[int]): Duration of the poll in
+ minutes for a tweet with a poll. This is only required
+ if the request includes poll_options.
+ quote_tweet_id (Optional[Union[int, str]]): Link to the tweet being
+ quoted.
+
+ Returns:
+ str: A message indicating the success of the tweet creation,
+ including the tweet ID and text. If the request to the
+ Twitter API is not successful, the return is an error message.
+
+ Note:
+ You can only provide either the `quote_tweet_id` parameter or
+ the pair of `poll_duration_minutes` and `poll_options` parameters,
+ not both.
+
+ Reference:
+ https://developer.x.com/en/docs/x-api/tweets/manage-tweets/api-reference/post-tweets
"""
+ auth = OAuth1(
+ os.getenv("TWITTER_CONSUMER_KEY"),
+ os.getenv("TWITTER_CONSUMER_SECRET"),
+ os.getenv("TWITTER_ACCESS_TOKEN"),
+ os.getenv("TWITTER_ACCESS_TOKEN_SECRET"),
+ )
+ url = "https://api.x.com/2/tweets"
+
+ # Validate text
+ if text is None:
+ return "Text cannot be None"
+
+ if len(text) > TWEET_TEXT_LIMIT:
+ return f"Text must not exceed {TWEET_TEXT_LIMIT} characters."
+
+ # Validate poll options and duration
+ if (poll_options is None) != (poll_duration_minutes is None):
+ return (
+ "Error: Both `poll_options` and `poll_duration_minutes` must "
+ "be provided together or not at all."
+ )
- def create_tweet(
- self,
- *,
- text: str,
- poll_options: Optional[List[str]] = None,
- poll_duration_minutes: Optional[int] = None,
- quote_tweet_id: Optional[Union[int, str]] = None,
- ) -> str:
- r"""Creates a new tweet, optionally including a poll or a quote tweet,
- or simply a text-only tweet.
-
- This function sends a POST request to the Twitter API to create a new
- tweet. The tweet can be a text-only tweet, or optionally include a poll
- or be a quote tweet. A confirmation prompt is presented to the user
- before the tweet is created.
-
- Args:
- text (str): The text of the tweet. The Twitter character limit for
- a single tweet is 280 characters.
- poll_options (Optional[List[str]]): A list of poll options for a
- tweet with a poll.
- poll_duration_minutes (Optional[int]): Duration of the poll in
- minutes for a tweet with a poll. This is only required
- if the request includes poll_options.
- quote_tweet_id (Optional[Union[int, str]]): Link to the tweet being
- quoted.
-
- Note:
- You can only provide either the `quote_tweet_id` parameter or
- the pair of `poll_duration_minutes` and `poll_options` parameters,
- not both.
-
- Returns:
- str: A message indicating the success of the tweet creation,
- including the tweet ID and text. If the request to the
- Twitter API is not successful, the return is an error message.
-
- Reference:
- https://developer.twitter.com/en/docs/twitter-api/tweets/
- manage-tweets/api-reference/post-tweets
- https://github.com/xdevplatform/Twitter-API-v2-sample-code/blob/
- main/Manage-Tweets/create_tweet.py
- """
- # validate text
- if text is None:
- return "Text cannot be None"
- elif len(text) > TWEET_TEXT_LIMIT:
- return "Text must not exceed 280 characters."
-
- # Validate poll options and duration
- if (poll_options is None) != (poll_duration_minutes is None):
- return (
- "Error: Both `poll_options` and `poll_duration_minutes` must "
- "be provided together or not at all."
- )
-
- # Validate exclusive parameters
- if quote_tweet_id is not None and (
- poll_options or poll_duration_minutes
- ):
- return (
- "Error: Cannot provide both `quote_tweet_id` and "
- "(`poll_options` or `poll_duration_minutes`)."
- )
-
- # Print the parameters that are not None
- params = {
- "text": text,
- "poll_options": poll_options,
- "poll_duration_minutes": poll_duration_minutes,
- "quote_tweet_id": quote_tweet_id,
- }
- print("You are going to create a tweet with following parameters:")
- for key, value in params.items():
- if value is not None:
- print(f"{key}: {value}")
-
- # Add a confirmation prompt at the beginning of the function
- confirm = input(
- "Are you sure you want to create this tweet? (yes/no): "
+ # Validate exclusive parameters
+ if quote_tweet_id is not None and (poll_options or poll_duration_minutes):
+ return (
+ "Error: Cannot provide both `quote_tweet_id` and "
+ "(`poll_options` or `poll_duration_minutes`)."
)
- if confirm.lower() != "yes":
- return "Execution cancelled by the user."
- oauth = self._get_oauth_session()
- json_data = {}
+ payload: Dict[str, Any] = {"text": text}
- if poll_options is not None and poll_duration_minutes is not None:
- json_data["poll"] = {
- "options": poll_options,
- "duration_minutes": poll_duration_minutes,
- }
+ if poll_options is not None and poll_duration_minutes is not None:
+ payload["poll"] = {
+ "options": poll_options,
+ "duration_minutes": poll_duration_minutes,
+ }
- if quote_tweet_id is not None:
- json_data["quote_tweet_id"] = str(quote_tweet_id) # type: ignore[assignment]
+ if quote_tweet_id is not None:
+ payload["quote_tweet_id"] = str(quote_tweet_id)
- json_data["text"] = text # type: ignore[assignment]
+ # Making the request
+ response = requests.post(url, auth=auth, json=payload)
- # Making the request
- response = oauth.post(
- "https://api.twitter.com/2/tweets",
- json=json_data,
+ if response.status_code != HTTPStatus.CREATED:
+ error_type = _handle_http_error(response)
+ return (
+ f"Request returned a(n) {error_type}: "
+ f"{response.status_code} {response.text}"
)
- if response.status_code != HTTPStatus.CREATED:
- error_type = self._handle_http_error(response)
- # use string concatenation to satisfy flake8
- return (
- "Request returned a(n) "
- + str(error_type)
- + ": "
- + str(response.status_code)
- + " "
- + response.text
- )
-
- # Saving the response as JSON
- json_response = response.json()
-
- tweet_id = json_response["data"]["id"]
- tweet_text = json_response["data"]["text"]
-
- response_str = (
- f"Create tweet successful. "
- f"The tweet ID is: {tweet_id}. "
- f"The tweet text is: '{tweet_text}'."
- )
+ json_response = response.json()
+ tweet_id = json_response["data"]["id"]
+ tweet_text = json_response["data"]["text"]
- return response_str
+ return f"Create tweet {tweet_id} successful with content {tweet_text}."
- def delete_tweet(self, tweet_id: str) -> str:
- r"""Deletes a tweet with the specified ID for an authorized user.
- This function sends a DELETE request to the Twitter API to delete
- a tweet with the specified ID. Before sending the request, it
- prompts the user to confirm the deletion.
+@api_keys_required(
+ "TWITTER_CONSUMER_KEY",
+ "TWITTER_CONSUMER_SECRET",
+ "TWITTER_ACCESS_TOKEN",
+ "TWITTER_ACCESS_TOKEN_SECRET",
+)
+def delete_tweet(tweet_id: str) -> str:
+ r"""Deletes a tweet with the specified ID for an authorized user.
- Args:
- tweet_id (str): The ID of the tweet to delete.
+ This function sends a DELETE request to the Twitter API to delete
+ a tweet with the specified ID. Before sending the request, it
+ prompts the user to confirm the deletion.
- Returns:
- str: A message indicating the result of the deletion. If the
- deletion was successful, the message includes the ID of the
- deleted tweet. If the deletion was not successful, the message
- includes an error message.
-
- Reference:
- https://developer.twitter.com/en/docs/twitter-api/tweets/
- manage-tweets/api-reference/delete-tweets-id
- """
- # Print the parameters that are not None
- if tweet_id is not None:
- print(
- f"You are going to delete a tweet with the following "
- f"ID: {tweet_id}"
- )
-
- # Add a confirmation prompt at the beginning of the function
- confirm = input(
- "Are you sure you want to delete this tweet? (yes/no): "
- )
- if confirm.lower() != "yes":
- return "Execution cancelled by the user."
+ Args:
+ tweet_id (str): The ID of the tweet to delete.
- oauth = self._get_oauth_session()
+ Returns:
+ str: A message indicating the result of the deletion. If the
+ deletion was successful, the message includes the ID of the
+ deleted tweet. If the deletion was not successful, the message
+ includes an error message.
- # Making the request
- response = oauth.delete(
- f"https://api.twitter.com/2/tweets/{tweet_id}",
+ Reference:
+ https://developer.x.com/en/docs/x-api/tweets/manage-tweets/api-reference/delete-tweets-id
+ """
+ auth = OAuth1(
+ os.getenv("TWITTER_CONSUMER_KEY"),
+ os.getenv("TWITTER_CONSUMER_SECRET"),
+ os.getenv("TWITTER_ACCESS_TOKEN"),
+ os.getenv("TWITTER_ACCESS_TOKEN_SECRET"),
+ )
+ url = f"https://api.x.com/2/tweets/{tweet_id}"
+ response = requests.delete(url, auth=auth)
+
+ if response.status_code != HTTPStatus.OK:
+ error_type = _handle_http_error(response)
+ return (
+ f"Request returned a(n) {error_type}: "
+ f"{response.status_code} {response.text}"
)
- if response.status_code != HTTPStatus.OK:
- error_type = self._handle_http_error(response)
- # use string concatenation to satisfy flake8
- return (
- "Request returned a(n) "
- + str(error_type)
- + ": "
- + str(response.status_code)
- + " "
- + response.text
- )
-
- # Saving the response as JSON
- json_response = response.json()
- # `deleted_status` may be True or False.
- # Defaults to False if not found.
- deleted_status = json_response.get("data", {}).get("deleted", False)
- response_str = (
- f"Delete tweet successful: {deleted_status}. "
- f"The tweet ID is: {tweet_id}. "
+ json_response = response.json()
+
+ # `deleted_status` may be True or False.
+ # Defaults to False if not found.
+ deleted_status = json_response.get("data", {}).get("deleted", False)
+ if not deleted_status:
+ return (
+ f"The tweet with ID {tweet_id} was not deleted. "
+ "Please check the tweet ID and try again."
)
- return response_str
- def get_my_user_profile(self) -> str:
- r"""Retrieves and formats the authenticated user's Twitter
- profile info.
+ return f"Delete tweet {tweet_id} successful."
- This function sends a GET request to the Twitter API to retrieve the
- authenticated user's profile information, including their pinned tweet.
- It then formats this information into a readable report.
- Returns:
- str: A formatted report of the authenticated user's Twitter profile
- information. This includes their ID, name, username,
- description, location, most recent tweet ID, profile image URL,
- account creation date, protection status, verification type,
- public metrics, and pinned tweet information. If the request to
- the Twitter API is not successful,
- the return is an error message.
-
- Reference:
- https://developer.twitter.com/en/docs/twitter-api/users/lookup/
- api-reference/get-users-me
- """
- oauth = self._get_oauth_session()
-
- tweet_fields = ["created_at", "text"]
- user_fields = [
- "created_at",
- "description",
- "id",
- "location",
- "most_recent_tweet_id",
- "name",
- "pinned_tweet_id",
- "profile_image_url",
- "protected",
- "public_metrics",
- "url",
- "username",
- "verified_type",
- ]
- params = {
- "expansions": "pinned_tweet_id",
- "tweet.fields": ",".join(tweet_fields),
- "user.fields": ",".join(user_fields),
- }
+@api_keys_required(
+ "TWITTER_CONSUMER_KEY",
+ "TWITTER_CONSUMER_SECRET",
+ "TWITTER_ACCESS_TOKEN",
+ "TWITTER_ACCESS_TOKEN_SECRET",
+)
+def get_my_user_profile() -> str:
+ r"""Retrieves the authenticated user's Twitter profile info.
+
+ This function sends a GET request to the Twitter API to retrieve the
+ authenticated user's profile information, including their pinned tweet.
+ It then formats this information into a readable report.
+
+ Returns:
+ str: A formatted report of the authenticated user's Twitter profile
+ information. This includes their ID, name, username,
+ description, location, most recent tweet ID, profile image URL,
+ account creation date, protection status, verification type,
+ public metrics, and pinned tweet information. If the request to
+ the Twitter API is not successful, the return is an error message.
+
+ Reference:
+ https://developer.x.com/en/docs/x-api/users/lookup/api-reference/get-users-me
+ """
+ return _get_user_info()
+
+
+@api_keys_required(
+ "TWITTER_CONSUMER_KEY",
+ "TWITTER_CONSUMER_SECRET",
+ "TWITTER_ACCESS_TOKEN",
+ "TWITTER_ACCESS_TOKEN_SECRET",
+)
+def get_user_by_username(username: str) -> str:
+ r"""Retrieves one user's Twitter profile info by username (handle).
+
+ This function sends a GET request to the Twitter API to retrieve the
+ user's profile information, including their pinned tweet.
+ It then formats this information into a readable report.
+
+ Args:
+ username (str): The username (handle) of the user to retrieve.
+
+ Returns:
+ str: A formatted report of the user's Twitter profile information.
+ This includes their ID, name, username, description, location,
+ most recent tweet ID, profile image URL, account creation date,
+ protection status, verification type, public metrics, and
+ pinned tweet information. If the request to the Twitter API is
+ not successful, the return is an error message.
+
+ Reference:
+ https://developer.x.com/en/docs/x-api/users/lookup/api-reference/get-users-by-username-username
+ """
+ return _get_user_info(username)
- response = oauth.get(
- "https://api.twitter.com/2/users/me", params=params
+
+def _get_user_info(username: Optional[str] = None) -> str:
+ r"""Generates a formatted report of the user information from the
+ JSON response.
+
+ Args:
+ username (Optional[str], optional): The username of the user to
+ retrieve. If None, the function retrieves the authenticated
+ user's profile information. (default: :obj:`None`)
+
+ Returns:
+ str: A formatted report of the user's Twitter profile information.
+ """
+ oauth = OAuth1(
+ os.getenv("TWITTER_CONSUMER_KEY"),
+ os.getenv("TWITTER_CONSUMER_SECRET"),
+ os.getenv("TWITTER_ACCESS_TOKEN"),
+ os.getenv("TWITTER_ACCESS_TOKEN_SECRET"),
+ )
+ url = (
+ f"https://api.x.com/2/users/by/username/{username}"
+ if username
+ else "https://api.x.com/2/users/me"
+ )
+
+ tweet_fields = ["created_at", "text"]
+ user_fields = [
+ "created_at",
+ "description",
+ "id",
+ "location",
+ "most_recent_tweet_id",
+ "name",
+ "pinned_tweet_id",
+ "profile_image_url",
+ "protected",
+ "public_metrics",
+ "url",
+ "username",
+ "verified_type",
+ ]
+ params = {
+ "expansions": "pinned_tweet_id",
+ "tweet.fields": ",".join(tweet_fields),
+ "user.fields": ",".join(user_fields),
+ }
+
+ response = requests.get(url, auth=oauth, params=params)
+
+ if response.status_code != HTTPStatus.OK:
+ error_type = _handle_http_error(response)
+ return (
+ f"Request returned a(n) {error_type}: "
+ f"{response.status_code} {response.text}"
)
- if response.status_code != HTTPStatus.OK:
- error_type = self._handle_http_error(response)
- error_message = "Request returned a(n) {}: {} {}".format(
- error_type, response.status_code, response.text
- )
- return error_message
+ json_response = response.json()
+
+ user_info = json_response.get("data", {})
+ pinned_tweet = json_response.get("includes", {}).get("tweets", [{}])[0]
+
+ user_report_entries = [
+ f"ID: {user_info['id']}",
+ f"Name: {user_info['name']}",
+ f"Username: {user_info['username']}",
+ ]
+
+ # Define the part of keys that need to be repeatedly processed
+ user_info_keys = [
+ "description",
+ "location",
+ "most_recent_tweet_id",
+ "profile_image_url",
+ ]
+ for key in user_info_keys:
+ if not (value := user_info.get(key)):
+ continue
+ new_key = key.replace('_', ' ').capitalize()
+ user_report_entries.append(f"{new_key}: {value}")
+
+ if "created_at" in user_info:
+ created_at = datetime.datetime.strptime(
+ user_info["created_at"], "%Y-%m-%dT%H:%M:%S.%fZ"
+ )
+ date_str = created_at.strftime('%B %d, %Y at %H:%M:%S')
+ user_report_entries.append(f"Account created at: {date_str}")
+
+ protection_status = "private" if user_info["protected"] else "public"
+ user_report_entries.append(
+ f"Protected: This user's Tweets are {protection_status}"
+ )
+
+ verification_messages = {
+ "blue": (
+ "The user has a blue verification, typically reserved for "
+ "public figures, celebrities, or global brands"
+ ),
+ "business": (
+ "The user has a business verification, typically "
+ "reserved for businesses and corporations"
+ ),
+ "government": (
+ "The user has a government verification, typically "
+ "reserved for government officials or entities"
+ ),
+ "none": "The user is not verified",
+ }
+ verification_type = user_info.get("verified_type", "none")
+ user_report_entries.append(
+ f"Verified type: {verification_messages.get(verification_type)}"
+ )
+
+ if "public_metrics" in user_info:
+ metrics = user_info["public_metrics"]
+ user_report_entries.append(
+ f"Public metrics: "
+ f"The user has {metrics.get('followers_count', 0)} followers, "
+ f"is following {metrics.get('following_count', 0)} users, "
+ f"has made {metrics.get('tweet_count', 0)} tweets, "
+ f"is listed in {metrics.get('listed_count', 0)} lists, "
+ f"and has received {metrics.get('like_count', 0)} likes"
+ )
- json_response = response.json()
-
- user_info = json_response.get('data', {})
- tweets = json_response.get('includes', {}).get('tweets', [{}])[0]
-
- user_report = ""
- user_report += f"ID: {user_info['id']}. "
- user_report += f"Name: {user_info['name']}. "
- user_report += f"Username: {user_info['username']}. "
-
- # Define the part of keys that need to be repeatedly processed
- user_info_keys = [
- 'description',
- 'location',
- 'most_recent_tweet_id',
- 'profile_image_url',
- ]
- for key in user_info_keys:
- value = user_info.get(key)
- if user_info.get(key):
- user_report += (
- f"{key.replace('_', ' ').capitalize()}: {value}. "
- )
-
- if 'created_at' in user_info:
- created_at = datetime.datetime.strptime(
- user_info['created_at'], "%Y-%m-%dT%H:%M:%S.%fZ"
- )
- date_str = created_at.strftime('%B %d, %Y at %H:%M:%S')
- user_report += f"Account created at: {date_str}. "
-
- protection_status = "private" if user_info['protected'] else "public"
- user_report += (
- f"Protected: This user's Tweets are {protection_status}. "
+ if "pinned_tweet_id" in user_info:
+ user_report_entries.append(
+ f"Pinned tweet ID: {user_info['pinned_tweet_id']}"
)
- verification_messages = {
- 'blue': (
- "The user has a blue verification, typically reserved for "
- "public figures, celebrities, or global brands. "
- ),
- 'business': (
- "The user has a business verification, typically "
- "reserved for businesses and corporations. "
- ),
- 'government': (
- "The user has a government verification, typically "
- "reserved for government officials or entities. "
- ),
- 'none': "The user is not verified. ",
- }
- verification_type = user_info.get('verified_type', 'none')
- user_report += (
- f"Verified type: {verification_messages.get(verification_type)}"
+ if "created_at" in pinned_tweet and "text" in pinned_tweet:
+ tweet_created_at = datetime.datetime.strptime(
+ pinned_tweet["created_at"], "%Y-%m-%dT%H:%M:%S.%fZ"
+ )
+ user_report_entries.append(
+ f"Pinned tweet information: Pinned tweet created at "
+ f"{tweet_created_at.strftime('%B %d, %Y at %H:%M:%S')} "
+ f"with text: '{pinned_tweet['text']}'"
)
- if 'public_metrics' in user_info:
- user_report += "Public metrics: "
- metrics = user_info['public_metrics']
- user_report += (
- f"The user has {metrics.get('followers_count', 0)} followers, "
- f"is following {metrics.get('following_count', 0)} users, "
- f"has made {metrics.get('tweet_count', 0)} tweets, "
- f"is listed in {metrics.get('listed_count', 0)} lists, "
- f"and has received {metrics.get('like_count', 0)} likes. "
- )
-
- if 'pinned_tweet_id' in user_info:
- user_report += f"Pinned tweet ID: {user_info['pinned_tweet_id']}. "
-
- if 'created_at' in tweets and 'text' in tweets:
- user_report += "\nPinned tweet information: "
- tweet_created_at = datetime.datetime.strptime(
- tweets['created_at'], "%Y-%m-%dT%H:%M:%S.%fZ"
- )
- user_report += (
- f"Pinned tweet created at "
- f"{tweet_created_at.strftime('%B %d, %Y at %H:%M:%S')} "
- f"with text: '{tweets['text']}'."
- )
-
- return user_report
+ return "\n".join(user_report_entries)
- 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.create_tweet),
- FunctionTool(self.delete_tweet),
- FunctionTool(self.get_my_user_profile),
- ]
+def _handle_http_error(response: requests.Response) -> str:
+ r"""Handles the HTTP response by checking the status code and
+ returning an appropriate message if there is an error.
- def _get_twitter_api_key(self) -> Tuple[str, str]:
- r"""Retrieve the Twitter API key and secret from environment variables.
+ Args:
+ response (requests.Response): The HTTP response to handle.
- Returns:
- Tuple[str, str]: A tuple containing the Twitter API key and secret.
+ Returns:
+ str: A string describing the error, if any. If there is no error,
+ the function returns an "Unexpected Exception" message.
- Raises:
- ValueError: If the API key or secret is not found in the
- environment variables.
- """
- # Get `TWITTER_CONSUMER_KEY` and `TWITTER_CONSUMER_SECRET` here:
- # https://developer.twitter.com/en/portal/products/free
- TWITTER_CONSUMER_KEY = os.environ.get("TWITTER_CONSUMER_KEY")
- TWITTER_CONSUMER_SECRET = os.environ.get("TWITTER_CONSUMER_SECRET")
-
- if not TWITTER_CONSUMER_KEY or not TWITTER_CONSUMER_SECRET:
- missing_keys = ", ".join(
- [
- "TWITTER_CONSUMER_KEY" if not TWITTER_CONSUMER_KEY else "",
- "TWITTER_CONSUMER_SECRET"
- if not TWITTER_CONSUMER_SECRET
- else "",
- ]
- ).strip(", ")
- raise ValueError(
- f"{missing_keys} not found in environment variables. Get them "
- "here: `https://developer.twitter.com/en/portal/products/free`."
- )
- return TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET
-
- def _get_oauth_session(self) -> requests.Session:
- r"""Initiates an OAuth1Session with Twitter's API and returns it.
-
- The function first fetches a request token, then prompts the user to
- authorize the application. After the user has authorized the
- application and provided a verifier (PIN), the function fetches an
- access token. Finally, a new OAuth1Session is created with the access
- token and returned.
-
- Raises:
- RuntimeError: If an error occurs while fetching the OAuth access
- token or the OAuth request token.
+ Reference:
+ https://github.com/tweepy/tweepy/blob/master/tweepy/client.py#L64
+ """
+ if response.status_code in responses:
+ # For 5xx server errors, return "Twitter Server Error"
+ if 500 <= response.status_code < 600:
+ return "Twitter Server Error"
+ else:
+ error_message = responses[response.status_code] + " Error"
+ return error_message
+ elif not 200 <= response.status_code < 300:
+ return "HTTP Exception"
+ else:
+ return "Unexpected Exception"
- Returns:
- requests_oauthlib.OAuth1Session: An OAuth1Session object
- authenticated with the user's access token.
-
- Reference:
- https://github.com/twitterdev/Twitter-API-v2-sample-code/blob/main/
- Manage-Tweets/create_tweet.py
- https://github.com/twitterdev/Twitter-API-v2-sample-code/blob/main/
- User-Lookup/get_users_me_user_context.py
- """
- try:
- from requests_oauthlib import OAuth1Session
- except ImportError:
- raise ImportError(
- "Please install `requests_oauthlib` first. You can "
- "install it by running `pip install "
- "requests_oauthlib`."
- )
-
- consumer_key, consumer_secret = self._get_twitter_api_key()
-
- # Get request token
- request_token_url = (
- "https://api.twitter.com/oauth/request_token"
- "?oauth_callback=oob&x_auth_access_type=write"
- )
- oauth = OAuth1Session(consumer_key, client_secret=consumer_secret)
-
- try:
- fetch_response = oauth.fetch_request_token(request_token_url)
- except Exception as e:
- raise RuntimeError(
- f"Error occurred while fetching the OAuth access token: {e}"
- )
-
- resource_owner_key = fetch_response.get("oauth_token")
- resource_owner_secret = fetch_response.get("oauth_token_secret")
-
- # Get authorization
- base_authorization_url = "https://api.twitter.com/oauth/authorize"
- authorization_url = oauth.authorization_url(base_authorization_url)
- print("Please go here and authorize: %s" % authorization_url)
- verifier = input("Paste the PIN here: ")
-
- # Get the access token
- access_token_url = "https://api.twitter.com/oauth/access_token"
- oauth = OAuth1Session(
- consumer_key,
- client_secret=consumer_secret,
- resource_owner_key=resource_owner_key,
- resource_owner_secret=resource_owner_secret,
- verifier=verifier,
- )
- try:
- oauth_tokens = oauth.fetch_access_token(access_token_url)
- except Exception as e:
- raise RuntimeError(
- f"Error occurred while fetching the OAuth request token: {e}"
- )
-
- # Create a new OAuth1Session with the access token
- oauth = OAuth1Session(
- consumer_key,
- client_secret=consumer_secret,
- resource_owner_key=oauth_tokens["oauth_token"],
- resource_owner_secret=oauth_tokens["oauth_token_secret"],
- )
- return oauth
+TWITTER_FUNCS = [
+ FunctionTool(create_tweet),
+ FunctionTool(delete_tweet),
+ FunctionTool(get_my_user_profile),
+ FunctionTool(get_user_by_username),
+]
- def _handle_http_error(self, response: requests.Response) -> str:
- r"""Handles the HTTP response by checking the status code and
- returning an appropriate message if there is an error.
- Args:
- response (requests.Response): The HTTP response to handle.
+class TwitterToolkit(BaseToolkit):
+ r"""A class representing a toolkit for Twitter operations.
- Returns:
- str: A string describing the error, if any. If there is no error,
- the function returns an "Unexpected Exception" message.
+ This class provides methods for creating a tweet, deleting a tweet, and
+ getting the authenticated user's profile information.
+
+ References:
+ https://developer.x.com/en/portal/dashboard
+
+ Notes:
+ To use this toolkit, you need to set the following environment
+ variables:
+ - TWITTER_CONSUMER_KEY: The consumer key for the Twitter API.
+ - TWITTER_CONSUMER_SECRET: The consumer secret for the Twitter API.
+ - TWITTER_ACCESS_TOKEN: The access token for the Twitter API.
+ - TWITTER_ACCESS_TOKEN_SECRET: The access token secret for the Twitter
+ API.
+ """
- Reference:
- https://github.com/tweepy/tweepy/blob/master/tweepy/client.py#L64
+ 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.
"""
- if response.status_code in responses:
- # For 5xx server errors, return "Twitter Server Error"
- if 500 <= response.status_code < 600:
- return "Twitter Server Error"
- else:
- error_message = responses[response.status_code] + " Error"
- return error_message
- elif not 200 <= response.status_code < 300:
- return "HTTP Exception"
- else:
- return "Unexpected Exception"
+ return TWITTER_FUNCS
diff --git a/camel/utils/commons.py b/camel/utils/commons.py
index c79274d60..7ed5fee56 100644
--- a/camel/utils/commons.py
+++ b/camel/utils/commons.py
@@ -257,18 +257,18 @@ def api_keys_required(*required_keys: str) -> Callable[[F], F]:
def decorator(func: F) -> F:
@wraps(func)
- def wrapper(self, *args: Any, **kwargs: Any) -> Any:
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
missing_environment_keys = [
k for k in required_keys if k not in os.environ
]
if (
- not getattr(self, '_api_key', None)
+ not (args and getattr(args[0], '_api_key', None))
and missing_environment_keys
):
raise ValueError(
f"Missing API keys: {', '.join(missing_environment_keys)}"
)
- return func(self, *args, **kwargs)
+ return func(*args, **kwargs)
return cast(F, wrapper)
diff --git a/examples/toolkits/post_weather_on_twitter.py b/examples/toolkits/post_weather_on_twitter.py
new file mode 100644
index 000000000..598879bc8
--- /dev/null
+++ b/examples/toolkits/post_weather_on_twitter.py
@@ -0,0 +1,62 @@
+# =========== 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 colorama import Fore
+
+from camel.agents import ChatAgent
+from camel.messages import BaseMessage
+from camel.toolkits import SEARCH_FUNCS, TWITTER_FUNCS, WEATHER_FUNCS
+from camel.utils import print_text_animated
+
+
+def main():
+ """
+ To run this, you need to set the following environment variables:
+ - TWITTER_CONSUMER_KEY
+ - TWITTER_CONSUMER_SECRET
+ - TWITTER_ACCESS_TOKEN
+ - TWITTER_ACCESS_TOKEN_SECRET
+ - OPENWEATHERMAP_API_KEY
+ - GOOGLE_API_KEY
+ - SEARCH_ENGINE_ID
+ """
+
+ sys_msg = BaseMessage.make_assistant_message(
+ role_name="Assistant",
+ content="You are a helpful agent with multiple tools.",
+ )
+
+ agent = ChatAgent(
+ system_message=sys_msg,
+ tools=[*TWITTER_FUNCS, *WEATHER_FUNCS, *SEARCH_FUNCS],
+ )
+
+ usr_msg = BaseMessage.make_user_message(
+ role_name="User",
+ content="I'm in Chicago and want to travel to Oxford today. Make a "
+ "travel plan for me, considering the weather today. Also announce my "
+ "plan on Twitter from my perspective.",
+ )
+
+ response = agent.step(usr_msg)
+
+ for tool_call in response.info["tool_calls"]:
+ print(f"{Fore.YELLOW}{tool_call}{Fore.RESET}\n======")
+
+ print_text_animated(
+ f"{Fore.GREEN}{response.msg.content}{Fore.RESET}", delay=0.005
+ )
+
+
+if __name__ == '__main__':
+ main()
diff --git a/poetry.lock b/poetry.lock
index fdb76b942..9bd9fe44f 100644
--- a/poetry.lock
+++ b/poetry.lock
@@ -7340,6 +7340,11 @@ files = [
{file = "scikit_learn-1.5.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f60021ec1574e56632be2a36b946f8143bf4e5e6af4a06d85281adc22938e0dd"},
{file = "scikit_learn-1.5.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:394397841449853c2290a32050382edaec3da89e35b3e03d6cc966aebc6a8ae6"},
{file = "scikit_learn-1.5.2-cp312-cp312-win_amd64.whl", hash = "sha256:57cc1786cfd6bd118220a92ede80270132aa353647684efa385a74244a41e3b1"},
+ {file = "scikit_learn-1.5.2-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:e9a702e2de732bbb20d3bad29ebd77fc05a6b427dc49964300340e4c9328b3f5"},
+ {file = "scikit_learn-1.5.2-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:b0768ad641981f5d3a198430a1d31c3e044ed2e8a6f22166b4d546a5116d7908"},
+ {file = "scikit_learn-1.5.2-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:178ddd0a5cb0044464fc1bfc4cca5b1833bfc7bb022d70b05db8530da4bb3dd3"},
+ {file = "scikit_learn-1.5.2-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f7284ade780084d94505632241bf78c44ab3b6f1e8ccab3d2af58e0e950f9c12"},
+ {file = "scikit_learn-1.5.2-cp313-cp313-win_amd64.whl", hash = "sha256:b7b0f9a0b1040830d38c39b91b3a44e1b643f4b36e36567b80b7c6bd2202a27f"},
{file = "scikit_learn-1.5.2-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:757c7d514ddb00ae249832fe87100d9c73c6ea91423802872d9e74970a0e40b9"},
{file = "scikit_learn-1.5.2-cp39-cp39-macosx_12_0_arm64.whl", hash = "sha256:52788f48b5d8bca5c0736c175fa6bdaab2ef00a8f536cda698db61bd89c551c1"},
{file = "scikit_learn-1.5.2-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:643964678f4b5fbdc95cbf8aec638acc7aa70f5f79ee2cdad1eec3df4ba6ead8"},
@@ -8575,11 +8580,6 @@ files = [
{file = "triton-3.0.0-1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:34e509deb77f1c067d8640725ef00c5cbfcb2052a1a3cb6a6d343841f92624eb"},
{file = "triton-3.0.0-1-cp38-cp38-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:bcbf3b1c48af6a28011a5c40a5b3b9b5330530c3827716b5fbf6d7adcc1e53e9"},
{file = "triton-3.0.0-1-cp39-cp39-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:6e5727202f7078c56f91ff13ad0c1abab14a0e7f2c87e91b12b6f64f3e8ae609"},
- {file = "triton-3.0.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:39b052da883351fdf6be3d93cedae6db3b8e3988d3b09ed221bccecfa9612230"},
- {file = "triton-3.0.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:cd34f19a8582af96e6291d4afce25dac08cb2a5d218c599163761e8e0827208e"},
- {file = "triton-3.0.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0d5e10de8c011adeb7c878c6ce0dd6073b14367749e34467f1cff2bde1b78253"},
- {file = "triton-3.0.0-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:e8903767951bf86ec960b4fe4e21bc970055afc65e9d57e916d79ae3c93665e3"},
- {file = "triton-3.0.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:41004fb1ae9a53fcb3e970745feb87f0e3c94c6ce1ba86e95fa3b8537894bef7"},
]
[package.dependencies]
diff --git a/test/toolkits/test_twitter_function.py b/test/toolkits/test_twitter_function.py
index 9d7543abc..a1b067010 100644
--- a/test/toolkits/test_twitter_function.py
+++ b/test/toolkits/test_twitter_function.py
@@ -11,20 +11,28 @@
# See the License for the specific language governing permissions and
# limitations under the License.
# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========
+import textwrap
from unittest.mock import MagicMock, patch
import pytest
-from camel.toolkits import TwitterToolkit
+from camel.toolkits.twitter_toolkit import (
+ create_tweet,
+ delete_tweet,
+ get_my_user_profile,
+ get_user_by_username,
+)
-def twitter_toolkit():
- return TwitterToolkit()
[email protected](autouse=True)
+def set_env_vars(monkeypatch):
+ monkeypatch.setenv("TWITTER_CONSUMER_KEY", "12345")
+ monkeypatch.setenv("TWITTER_CONSUMER_SECRET", "12345")
+ monkeypatch.setenv("TWITTER_ACCESS_TOKEN", "12345")
+ monkeypatch.setenv("TWITTER_ACCESS_TOKEN_SECRET", "12345")
-def test_create_tweet(monkeypatch, twitter_toolkit):
- # Create a mock response object
+def test_create_tweet(monkeypatch):
mock_response = MagicMock()
mock_response.json.return_value = {
'data': {
@@ -35,76 +43,37 @@ def test_create_tweet(monkeypatch, twitter_toolkit):
}
mock_response.status_code = 201
- # Mock user input to confirm creating a tweet
- monkeypatch.setattr('builtins.input', lambda _: 'yes')
-
- # Capture the output of the print function
- captured_output = []
- monkeypatch.setattr('builtins.print', lambda x: captured_output.append(x))
-
- # Use patch to mock the get_oauth_session method
- patch_path = (
- 'camel.toolkits.twitter_toolkit.TwitterToolkit._get_oauth_session'
- )
- with patch(patch_path) as mock_get_oauth_session:
- # Configure the mock OAuth session's post method
- # to return the mock response object
- mock_get_oauth_session.return_value.post.return_value = mock_response
+ with patch(
+ "camel.toolkits.twitter_toolkit.requests.post"
+ ) as mock_requests_post:
+ mock_requests_post.return_value = mock_response
# Call the create_tweet function
- response = twitter_toolkit.create_tweet(text="Test tweet.")
+ response = create_tweet("Test tweet.")
- # Verify the output
- expected_start = (
- "You are going to create a tweet with following parameters:"
- )
- assert expected_start in captured_output
- assert "text: Test tweet." in captured_output
expected_response = (
- "Create tweet successful. The tweet ID is: "
- "12345. The tweet text is: 'Test tweet'."
+ "Create tweet 12345 successful with content Test tweet."
)
assert response == expected_response
-def test_delete_tweet(monkeypatch, twitter_toolkit):
- # Delete a mock response object
+def test_delete_tweet(monkeypatch):
mock_response = MagicMock()
mock_response.json.return_value = {'data': {'deleted': True}}
mock_response.status_code = 200
- # Mock user input to confirm creating a tweet
- monkeypatch.setattr('builtins.input', lambda _: 'yes')
-
- # Capture the output of the print function
- captured_output = []
- monkeypatch.setattr('builtins.print', lambda x: captured_output.append(x))
-
- # Use patch to mock the get_oauth_session method
- patch_path = (
- 'camel.toolkits.twitter_toolkit.TwitterToolkit._get_oauth_session'
- )
- with patch(patch_path) as mock_get_oauth_session:
- # Configure the mock OAuth session's delete method
- # to return the mock response object
- mock_get_oauth_session.return_value.delete.return_value = mock_response
-
- # Call the delete_tweet function
- response = twitter_toolkit.delete_tweet(tweet_id="11111")
+ with patch(
+ "camel.toolkits.twitter_toolkit.requests.delete"
+ ) as mock_requests_delete:
+ mock_requests_delete.return_value = mock_response
- # Verify the output
- expected_start = (
- "You are going to delete a tweet with the following ID: 11111"
- )
- assert expected_start in captured_output
- expected_response = (
- "Delete tweet successful: True. The tweet ID is: " "11111. "
- )
+ response = delete_tweet("11111")
+ expected_response = "Delete tweet 11111 successful."
assert response == expected_response
-def test_get_user_me(monkeypatch, twitter_toolkit):
- # Mocked JSON response, anonymized
+def test_get_user_me(monkeypatch):
+ mock_response = MagicMock()
mock_json_response = {
'data': {
'location': 'Some Location',
@@ -115,7 +84,7 @@ def test_get_user_me(monkeypatch, twitter_toolkit):
'protected': False,
'verified_type': 'none',
'id': '1234567890',
- 'username': 'AUsername',
+ 'username': 'myusername',
'public_metrics': {
'followers_count': 10,
'following_count': 20,
@@ -136,35 +105,96 @@ def test_get_user_me(monkeypatch, twitter_toolkit):
]
},
}
+ mock_response.json.return_value = mock_json_response
+ mock_response.status_code = 200
+
+ with patch(
+ "camel.toolkits.twitter_toolkit.requests.get"
+ ) as mock_requests_get:
+ mock_requests_get.return_value = mock_response
+ response = get_my_user_profile()
- # Use patch to mock the get_oauth_session method
- patch_path = (
- 'camel.toolkits.twitter_toolkit.TwitterToolkit._get_oauth_session'
- )
- with patch(patch_path) as mock_get_oauth_session:
- mock_response = MagicMock()
- mock_response.json.return_value = mock_json_response
- mock_response.status_code = 200
- mock_get_oauth_session.return_value.get.return_value = mock_response
+ # Verify the returned user information report
+ expected_report = textwrap.dedent(
+ """\
+ ID: 1234567890
+ Name: A Name
+ Username: myusername
+ Description: A description of the user.
+ Location: Some Location
+ Most recent tweet id: 1234567890123456789
+ Profile image url: https://example.com/image.jpg
+ Account created at: March 16, 2024 at 06:31:14
+ Protected: This user's Tweets are public
+ Verified type: The user is not verified
+ Public metrics: The user has 10 followers, is following 20 users, has made 30 tweets, is listed in 40 lists, and has received 50 likes
+ Pinned tweet ID: 9876543210987654321
+ Pinned tweet information: Pinned tweet created at April 17, 2024 at 12:40:01 with text: 'A tweet content.'
+ """ # noqa: E501
+ )
+
+ assert response.strip() == expected_report.strip()
+
+
+def test_get_user_by_username(monkeypatch):
+ mock_response = MagicMock()
+ mock_json_response = {
+ 'data': {
+ 'location': 'Another Location',
+ 'most_recent_tweet_id': '1234567890123456789',
+ 'pinned_tweet_id': '9876543210987654321',
+ 'description': 'A description of another user.',
+ 'name': 'A Name',
+ 'protected': False,
+ 'verified_type': 'none',
+ 'id': '1234567890',
+ 'username': 'anotherusername',
+ 'public_metrics': {
+ 'followers_count': 10,
+ 'following_count': 20,
+ 'tweet_count': 30,
+ 'listed_count': 40,
+ 'like_count': 50,
+ },
+ 'profile_image_url': 'https://example.com/image.jpg',
+ 'created_at': '2024-03-16T06:31:14.000Z',
+ },
+ 'includes': {
+ 'tweets': [
+ {
+ 'id': '9876543210987654321',
+ 'created_at': '2024-04-17T12:40:01.000Z',
+ 'text': 'A tweet content.',
+ }
+ ]
+ },
+ }
+ mock_response.json.return_value = mock_json_response
+ mock_response.status_code = 200
- # Call the get_user_me function
- response = twitter_toolkit.get_my_user_profile()
+ with patch(
+ "camel.toolkits.twitter_toolkit.requests.get"
+ ) as mock_requests_get:
+ mock_requests_get.return_value = mock_response
+ response = get_user_by_username("anotherusername")
# Verify the returned user information report
- expected_report = (
- "ID: 1234567890. Name: A Name. Username: AUsername. "
- "Description: A description of the user.. Location: Some "
- "Location. "
- "Most recent tweet id: 1234567890123456789. "
- "Profile image url: https://example.com/image.jpg. "
- "Account created at: March 16, 2024 at 06:31:14. "
- "Protected: This user's Tweets are public. "
- "Verified type: The user is not verified. "
- "Public metrics: The user has 10 followers, "
- "is following 20 users, has made 30 tweets, "
- "is listed in 40 lists, and has received 50 likes. "
- "Pinned tweet ID: 9876543210987654321. "
- "\nPinned tweet information: Pinned tweet created at "
- "April 17, 2024 at 12:40:01 with text: 'A tweet content.'."
+ expected_report = textwrap.dedent(
+ """\
+ ID: 1234567890
+ Name: A Name
+ Username: anotherusername
+ Description: A description of another user.
+ Location: Another Location
+ Most recent tweet id: 1234567890123456789
+ Profile image url: https://example.com/image.jpg
+ Account created at: March 16, 2024 at 06:31:14
+ Protected: This user's Tweets are public
+ Verified type: The user is not verified
+ Public metrics: The user has 10 followers, is following 20 users, has made 30 tweets, is listed in 40 lists, and has received 50 likes
+ Pinned tweet ID: 9876543210987654321
+ Pinned tweet information: Pinned tweet created at April 17, 2024 at 12:40:01 with text: 'A tweet content.'
+ """ # noqa: E501
)
- assert response == expected_report
+
+ assert response.strip() == expected_report.strip()