🐫 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
refactor: Code with dependencies_required decorator (#696)
Zheng Lu8032c7afe8e2
diff --git a/camel/functions/search_functions.py b/camel/functions/search_functions.pyindex e983edfb8..464ea0868 100644--- a/camel/functions/search_functions.py+++ b/camel/functions/search_functions.py@@ -15,8 +15,10 @@ import osfrom typing import Any, Dict, Listfrom camel.functions.openai_function import OpenAIFunction+from camel.utils import dependencies_required+@dependencies_required('wikipedia')def search_wiki(entity: str) -> str:r"""Search the entity in WikiPedia and return the summary of the requiredpage, containing factual information about the given entity.@@ -28,13 +30,7 @@ def search_wiki(entity: str) -> str:str: The search result. If the page corresponding to the entityexists, return the summary of this entity in a string."""- try:- import wikipedia- except ImportError:- raise ImportError(- "Please install `wikipedia` first. You can install it by running "- "`pip install wikipedia`."- )+ import wikipediaresult: str@@ -241,6 +237,7 @@ def search_google(return responses+@dependencies_required('wolframalpha')def query_wolfram_alpha(query: str, is_detailed: bool) -> str:r"""Queries Wolfram|Alpha and returns the result. Wolfram|Alpha is ananswer engine developed by Wolfram Research. It is offered as an online@@ -255,13 +252,7 @@ def query_wolfram_alpha(query: str, is_detailed: bool) -> str:Returns:str: The result from Wolfram Alpha, formatted as a string."""- try:- import wolframalpha- except ImportError:- raise ImportError(- "Please install `wolframalpha` first. You can install it by"- " running `pip install wolframalpha`."- )+ import wolframalphaWOLFRAMALPHA_APP_ID = os.environ.get('WOLFRAMALPHA_APP_ID')if not WOLFRAMALPHA_APP_ID:diff --git a/camel/functions/slack_functions.py b/camel/functions/slack_functions.pyindex bf2e58aba..60612de86 100644--- a/camel/functions/slack_functions.py+++ b/camel/functions/slack_functions.py@@ -19,6 +19,8 @@ import loggingimport osfrom typing import TYPE_CHECKING, List, Optional+from camel.utils import dependencies_required+if TYPE_CHECKING:from ssl import SSLContext@@ -29,6 +31,7 @@ from camel.functions import OpenAIFunctionlogger = logging.getLogger(__name__)+@dependencies_required('slack_sdk')def _login_slack(slack_token: Optional[str] = None,ssl: Optional[SSLContext] = None,@@ -50,13 +53,8 @@ def _login_slack(KeyError: If SLACK_BOT_TOKEN or SLACK_USER_TOKEN environment variablesare not set."""- try:- from slack_sdk import WebClient- except ImportError as e:- raise ImportError(- "Cannot import slack_sdk. Please install the package with \- `pip install slack_sdk`."- ) from e+ from slack_sdk import WebClient+if not slack_token:slack_token = os.environ.get("SLACK_BOT_TOKEN") or os.environ.get("SLACK_USER_TOKEN"diff --git a/camel/functions/twitter_function.py b/camel/functions/twitter_function.pyindex 70ed6e2ad..c6dfcf7fb 100644--- a/camel/functions/twitter_function.py+++ b/camel/functions/twitter_function.py@@ -20,6 +20,7 @@ from typing import List, Optional, Tuple, Unionimport requestsfrom camel.functions import OpenAIFunction+from camel.utils import dependencies_requiredTWEET_TEXT_LIMIT = 280@@ -55,6 +56,7 @@ def get_twitter_api_key() -> Tuple[str, str]:return TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET+@dependencies_required('requests_oauthlib')def get_oauth_session() -> requests.Session:r'''Initiates an OAuth1Session with Twitter's API and returns it.@@ -75,14 +77,7 @@ def get_oauth_session() -> requests.Session:https://github.com/twitterdev/Twitter-API-v2-sample-code/blob/main/Manage-Tweets/create_tweet.pyhttps://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`."- )+ from requests_oauthlib import OAuth1Sessionconsumer_key, consumer_secret = get_twitter_api_key()diff --git a/camel/functions/weather_functions.py b/camel/functions/weather_functions.pyindex e83383cdf..cf540c6ae 100644--- a/camel/functions/weather_functions.py+++ b/camel/functions/weather_functions.py@@ -15,6 +15,7 @@ import osfrom typing import List, Literalfrom camel.functions.openai_function import OpenAIFunction+from camel.utils import dependencies_requireddef get_openweathermap_api_key() -> str:@@ -37,6 +38,7 @@ def get_openweathermap_api_key() -> str:return OPENWEATHERMAP_API_KEY+@dependencies_required('pyowm')def get_weather_data(city: str,temp_units: Literal['kelvin', 'celsius', 'fahrenheit'] = 'kelvin',@@ -85,14 +87,7 @@ def get_weather_data("""# NOTE: This tool may not work as expected since the input arguments like# `time_units` should be enum types which are not supported yet.-- try:- import pyowm- except ImportError:- raise ImportError(- "Please install `pyowm` first. You can install it by running "- "`pip install pyowm`."- )+ import pyowmOPENWEATHERMAP_API_KEY = get_openweathermap_api_key()owm = pyowm.OWM(OPENWEATHERMAP_API_KEY)diff --git a/camel/loaders/base_io.py b/camel/loaders/base_io.pyindex 4804cd3ab..8ffde4b8b 100644--- a/camel/loaders/base_io.py+++ b/camel/loaders/base_io.py@@ -19,6 +19,8 @@ from hashlib import md5from io import BytesIOfrom typing import Any, Dict, List, Optional+from camel.utils import dependencies_required+class File(ABC):r"""Represents an uploaded file comprised of Documents"""@@ -94,6 +96,7 @@ def strip_consecutive_newlines(text: str) -> str:class DocxFile(File):@classmethod+ @dependencies_required('docx2txt')def from_bytes(cls, file: BytesIO) -> "DocxFile":r"""Creates a DocxFile object from a BytesIO object.@@ -104,15 +107,8 @@ class DocxFile(File):Returns:DocxFile: A DocxFile object."""- # Use docx2txt to extract text from docx files- try:- import docx2txt- except ImportError:- raise ImportError(- "Please install `docx2txt` first. "- "You can install it by running "- "`pip install docx2txt`."- )+ import docx2txt+text = docx2txt.process(file)text = strip_consecutive_newlines(text)# Create a dictionary with the extracted textdiff --git a/camel/loaders/unstructured_io.py b/camel/loaders/unstructured_io.pyindex 823c40a94..df9ceb1df 100644--- a/camel/loaders/unstructured_io.py+++ b/camel/loaders/unstructured_io.py@@ -16,6 +16,8 @@ from typing import Any, Dict, List, Literal, Optional, Tuple, Unionfrom unstructured.documents.elements import Element+from camel.utils import dependencies_required+class UnstructuredIO:r"""A class to handle various functionalities provided by the@@ -37,6 +39,7 @@ class UnstructuredIO:"""self._ensure_unstructured_version(self.UNSTRUCTURED_MIN_VERSION)+ @dependencies_required('unstructured')def _ensure_unstructured_version(self, min_version: str) -> None:r"""Validates that the installed 'Unstructured' library versionsatisfies the specified minimum version requirement. This function is@@ -58,12 +61,7 @@ class UnstructuredIO:strings."""from packaging import version-- try:- from unstructured.__version__ import __version__-- except ImportError as e:- raise ImportError("Package `unstructured` not installed.") from e+ from unstructured.__version__ import __version__# Use packaging.version to compare versionsmin_ver = version.parse(min_version)diff --git a/camel/retrievers/bm25_retriever.py b/camel/retrievers/bm25_retriever.pyindex 5bb0aa073..6a31024bb 100644--- a/camel/retrievers/bm25_retriever.py+++ b/camel/retrievers/bm25_retriever.py@@ -17,6 +17,7 @@ import numpy as npfrom camel.loaders import UnstructuredIOfrom camel.retrievers import BaseRetriever+from camel.utils import dependencies_requiredDEFAULT_TOP_K_RESULTS = 1@@ -40,16 +41,10 @@ class BM25Retriever(BaseRetriever):https://github.com/dorianbrown/rank_bm25"""+ @dependencies_required('rank_bm25')def __init__(self) -> None:r"""Initializes the BM25Retriever."""-- try:- from rank_bm25 import BM25Okapi- except ImportError as e:- raise ImportError(- "Package `rank_bm25` not installed, install by running 'pip "- "install rank_bm25'"- ) from e+ from rank_bm25 import BM25Okapiself.bm25: BM25Okapi = Noneself.content_input_path: str = ""diff --git a/camel/retrievers/cohere_rerank_retriever.py b/camel/retrievers/cohere_rerank_retriever.pyindex 527877d18..84d51cfa8 100644--- a/camel/retrievers/cohere_rerank_retriever.py+++ b/camel/retrievers/cohere_rerank_retriever.py@@ -15,6 +15,7 @@ import osfrom typing import Any, Dict, List, Optionalfrom camel.retrievers import BaseRetriever+from camel.utils import dependencies_requiredDEFAULT_TOP_K_RESULTS = 1@@ -32,6 +33,7 @@ class CohereRerankRetriever(BaseRetriever):https://txt.cohere.com/rerank/"""+ @dependencies_required('cohere')def __init__(self,model_name: str = "rerank-multilingual-v2.0",@@ -56,11 +58,7 @@ class CohereRerankRetriever(BaseRetriever):ValueError: If the API key is neither passed as an argument norset in the environment variable."""-- try:- import cohere- except ImportError as e:- raise ImportError("Package 'cohere' is not installed") from e+ import coheretry:self.api_key = api_key or os.environ["COHERE_API_KEY"]diff --git a/camel/storages/graph_storages/neo4j_graph.py b/camel/storages/graph_storages/neo4j_graph.pyindex c93b85117..df16de1c5 100644--- a/camel/storages/graph_storages/neo4j_graph.py+++ b/camel/storages/graph_storages/neo4j_graph.py@@ -16,6 +16,7 @@ from hashlib import md5from typing import Any, Dict, List, Optionalfrom camel.storages.graph_storages import BaseGraphStorage, GraphElement+from camel.utils import dependencies_requiredlogger = logging.getLogger(__name__)@@ -81,6 +82,7 @@ class Neo4jGraph(BaseGraphStorage):than `LIST_LIMIT` elements from results. Defaults to `False`."""+ @dependencies_required('neo4j')def __init__(self,url: str,@@ -91,13 +93,7 @@ class Neo4jGraph(BaseGraphStorage):truncate: bool = False,) -> None:r"""Create a new Neo4j graph instance."""- try:- import neo4j- except ImportError:- raise ValueError(- "Could not import neo4j python package. "- "Please install it with `pip install neo4j`."- )+ import neo4jself.driver = neo4j.GraphDatabase.driver(url, auth=(username, password)diff --git a/camel/storages/vectordb_storages/milvus.py b/camel/storages/vectordb_storages/milvus.pyindex f7f9076ae..38ae3dfd9 100644--- a/camel/storages/vectordb_storages/milvus.py+++ b/camel/storages/vectordb_storages/milvus.py@@ -23,6 +23,7 @@ from camel.storages.vectordb_storages import (VectorDBStatus,VectorRecord,)+from camel.utils import dependencies_requiredlogger = logging.getLogger(__name__)@@ -52,6 +53,7 @@ class MilvusStorage(BaseVectorStorage):ImportError: If `pymilvus` package is not installed."""+ @dependencies_required('pymilvus')def __init__(self,vector_dim: int,@@ -59,13 +61,7 @@ class MilvusStorage(BaseVectorStorage):collection_name: Optional[str] = None,**kwargs: Any,) -> None:- try:- from pymilvus import MilvusClient- except ImportError as exc:- raise ImportError(- "Please install `pymilvus` first. You can install it by "- "running `pip install pymilvus`."- ) from exc+ from pymilvus import MilvusClientself._client: MilvusClientself._create_client(url_and_api_key, **kwargs)diff --git a/camel/storages/vectordb_storages/qdrant.py b/camel/storages/vectordb_storages/qdrant.pyindex 7d67abe2e..fcb5bc0e9 100644--- a/camel/storages/vectordb_storages/qdrant.py+++ b/camel/storages/vectordb_storages/qdrant.py@@ -23,6 +23,7 @@ from camel.storages.vectordb_storages import (VectorRecord,)from camel.types import VectorDistance+from camel.utils import dependencies_required_qdrant_local_client_map: Dict[str, Tuple[Any, int]] = {}@@ -62,6 +63,7 @@ class QdrantStorage(BaseVectorStorage):be initialized with an in-memory storage (`":memory:"`)."""+ @dependencies_required('qdrant_client')def __init__(self,vector_dim: int,@@ -72,13 +74,7 @@ class QdrantStorage(BaseVectorStorage):delete_collection_on_del: bool = False,**kwargs: Any,) -> None:- try:- from qdrant_client import QdrantClient- except ImportError as exc:- raise ImportError(- "Please install `qdrant-client` first. You can install it by "- "running `pip install qdrant-client`."- ) from exc+ from qdrant_client import QdrantClientself._client: QdrantClientself._local_path: Optional[str] = Nonediff --git a/camel/toolkits/github_toolkit.py b/camel/toolkits/github_toolkit.pyindex caa8252fd..173649694 100644--- a/camel/toolkits/github_toolkit.py+++ b/camel/toolkits/github_toolkit.py@@ -18,8 +18,8 @@ from datetime import datetime, timedeltafrom typing import List, Optionalfrom camel.functions import OpenAIFunction--from .base import BaseToolkit+from camel.toolkits.base import BaseToolkit+from camel.utils import dependencies_required@dataclass@@ -130,6 +130,7 @@ class GithubToolkit(BaseToolkit):`get_github_access_token` method."""+ @dependencies_required('github')def __init__(self, repo_name: str, access_token: Optional[str] = None) -> None:@@ -144,13 +145,8 @@ class GithubToolkit(BaseToolkit):if access_token is None:access_token = self.get_github_access_token()- try:- from github import Auth, Github- except ImportError:- raise ImportError(- "Please install `github` first. You can install it by running "- "`pip install pygithub`."- )+ from github import Auth, Github+self.github = Github(auth=Auth.Token(access_token))self.repo = self.github.get_repo(repo_name)diff --git a/examples/bots/discord_bot.py b/examples/bots/discord_bot.pyindex 25e544ac5..735f2d8af 100644--- a/examples/bots/discord_bot.py+++ b/examples/bots/discord_bot.py@@ -17,6 +17,7 @@ from typing import TYPE_CHECKING, List, Optional, Unionfrom camel.agents import ChatAgentfrom camel.messages import BaseMessagefrom camel.retrievers import AutoRetriever+from camel.utils import dependencies_requiredif TYPE_CHECKING:from discord import Message@@ -37,6 +38,7 @@ class DiscordBot:return_detailed_info (bool): If show detailed info of the RAG response."""+ @dependencies_required('discord')def __init__(self,chat_agent: ChatAgent,@@ -61,13 +63,8 @@ class DiscordBot:" here: `https://discord.com/developers/applications`.")- try:- import discord- except ImportError:- raise ImportError(- "Please install `discord` first. You can install it by running"- " `python3 -m pip install -U discord.py`."- )+ import discord+intents = discord.Intents.default()intents.message_content = Trueself.client = discord.Client(intents=intents)diff --git a/examples/bots/telegram_bot.py b/examples/bots/telegram_bot.pyindex 374afd97b..51e22a83a 100644--- a/examples/bots/telegram_bot.py+++ b/examples/bots/telegram_bot.py@@ -16,6 +16,7 @@ from typing import TYPE_CHECKING, Optionalfrom camel.agents import ChatAgentfrom camel.messages import BaseMessage+from camel.utils import dependencies_required# Conditionally import telebot types only for type checkingif TYPE_CHECKING:@@ -30,6 +31,7 @@ class TelegramBot:telegram_token (str, optional): The bot token."""+ @dependencies_required('telebot')def __init__(self,chat_agent: ChatAgent,@@ -47,14 +49,8 @@ class TelegramBot:else:self.token = telegram_token- try:- import telebot # type: ignore[import-untyped]- except ImportError:- raise ImportError(- "Please install `telegram_bot` first. "- "You can install it by running "- "`pip install pyTelegramBotAPI`."- )+ import telebot # type: ignore[import-untyped]+self.bot = telebot.TeleBot(token=self.token)# Register the message handler within the constructor