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: Code with dependencies_required decorator (#696)

Zheng Lu8032c7afe8e2
diff --git a/camel/functions/search_functions.py b/camel/functions/search_functions.py
index e983edfb8..464ea0868 100644
--- a/camel/functions/search_functions.py
+++ b/camel/functions/search_functions.py
@@ -15,8 +15,10 @@ import os
from typing import Any, Dict, List
from 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 required
page, 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 entity
exists, 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 wikipedia
result: 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 an
answer 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 wolframalpha
WOLFRAMALPHA_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.py
index bf2e58aba..60612de86 100644
--- a/camel/functions/slack_functions.py
+++ b/camel/functions/slack_functions.py
@@ -19,6 +19,8 @@ import logging
import os
from 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 OpenAIFunction
logger = 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 variables
are 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.py
index 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, Union
import requests
from camel.functions import OpenAIFunction
+from camel.utils import dependencies_required
TWEET_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.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`."
- )
+ from requests_oauthlib import OAuth1Session
consumer_key, consumer_secret = get_twitter_api_key()
diff --git a/camel/functions/weather_functions.py b/camel/functions/weather_functions.py
index e83383cdf..cf540c6ae 100644
--- a/camel/functions/weather_functions.py
+++ b/camel/functions/weather_functions.py
@@ -15,6 +15,7 @@ import os
from typing import List, Literal
from camel.functions.openai_function import OpenAIFunction
+from camel.utils import dependencies_required
def 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 pyowm
OPENWEATHERMAP_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.py
index 4804cd3ab..8ffde4b8b 100644
--- a/camel/loaders/base_io.py
+++ b/camel/loaders/base_io.py
@@ -19,6 +19,8 @@ from hashlib import md5
from io import BytesIO
from 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 text
diff --git a/camel/loaders/unstructured_io.py b/camel/loaders/unstructured_io.py
index 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, Union
from 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 version
satisfies 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 versions
min_ver = version.parse(min_version)
diff --git a/camel/retrievers/bm25_retriever.py b/camel/retrievers/bm25_retriever.py
index 5bb0aa073..6a31024bb 100644
--- a/camel/retrievers/bm25_retriever.py
+++ b/camel/retrievers/bm25_retriever.py
@@ -17,6 +17,7 @@ import numpy as np
from camel.loaders import UnstructuredIO
from camel.retrievers import BaseRetriever
+from camel.utils import dependencies_required
DEFAULT_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 BM25Okapi
self.bm25: BM25Okapi = None
self.content_input_path: str = ""
diff --git a/camel/retrievers/cohere_rerank_retriever.py b/camel/retrievers/cohere_rerank_retriever.py
index 527877d18..84d51cfa8 100644
--- a/camel/retrievers/cohere_rerank_retriever.py
+++ b/camel/retrievers/cohere_rerank_retriever.py
@@ -15,6 +15,7 @@ import os
from typing import Any, Dict, List, Optional
from camel.retrievers import BaseRetriever
+from camel.utils import dependencies_required
DEFAULT_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 nor
set in the environment variable.
"""
-
- try:
- import cohere
- except ImportError as e:
- raise ImportError("Package 'cohere' is not installed") from e
+ import cohere
try:
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.py
index 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 md5
from typing import Any, Dict, List, Optional
from camel.storages.graph_storages import BaseGraphStorage, GraphElement
+from camel.utils import dependencies_required
logger = 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 neo4j
self.driver = neo4j.GraphDatabase.driver(
url, auth=(username, password)
diff --git a/camel/storages/vectordb_storages/milvus.py b/camel/storages/vectordb_storages/milvus.py
index 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_required
logger = 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 MilvusClient
self._client: MilvusClient
self._create_client(url_and_api_key, **kwargs)
diff --git a/camel/storages/vectordb_storages/qdrant.py b/camel/storages/vectordb_storages/qdrant.py
index 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 QdrantClient
self._client: QdrantClient
self._local_path: Optional[str] = None
diff --git a/camel/toolkits/github_toolkit.py b/camel/toolkits/github_toolkit.py
index caa8252fd..173649694 100644
--- a/camel/toolkits/github_toolkit.py
+++ b/camel/toolkits/github_toolkit.py
@@ -18,8 +18,8 @@ from datetime import datetime, timedelta
from typing import List, Optional
from 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.py
index 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, Union
from camel.agents import ChatAgent
from camel.messages import BaseMessage
from camel.retrievers import AutoRetriever
+from camel.utils import dependencies_required
if 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 = True
self.client = discord.Client(intents=intents)
diff --git a/examples/bots/telegram_bot.py b/examples/bots/telegram_bot.py
index 374afd97b..51e22a83a 100644
--- a/examples/bots/telegram_bot.py
+++ b/examples/bots/telegram_bot.py
@@ -16,6 +16,7 @@ from typing import TYPE_CHECKING, Optional
from camel.agents import ChatAgent
from camel.messages import BaseMessage
+from camel.utils import dependencies_required
# Conditionally import telebot types only for type checking
if 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