🐫 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(loaders): add dependencies_required/api_keys_required decorators to camel.loaders (#4110)
nuthalapativaruncad8b794d94e
diff --git a/camel/loaders/base_io.py b/camel/loaders/base_io.pyindex 8cff78014..967ec5c83 100644--- a/camel/loaders/base_io.py+++ b/camel/loaders/base_io.py@@ -190,6 +190,7 @@ class DocxFile(File):class PdfFile(File):@classmethod+ @dependencies_required('fitz')def from_bytes(cls, file: BytesIO, filename: str) -> "PdfFile":r"""Creates a PdfFile object from a BytesIO object.@@ -201,15 +202,8 @@ class PdfFile(File):Returns:PdfFile: A PdfFile object."""- # Use fitz to extract text from pdf files- try:- import fitz- except ImportError:- raise ImportError(- "Please install `PyMuPDF` first. "- "You can install it by running "- "`pip install PyMuPDF`."- )+ import fitz+pdf = fitz.open(stream=file.read(), filetype="pdf")docs = []for i, page in enumerate(pdf):@@ -291,6 +285,7 @@ class JsonFile(File):class HtmlFile(File):@classmethod+ @dependencies_required('bs4')def from_bytes(cls, file: BytesIO, filename: str) -> "HtmlFile":r"""Creates a HtmlFile object from a BytesIO object.@@ -302,15 +297,8 @@ class HtmlFile(File):Returns:HtmlFile: A HtmlFile object."""- # Parse the HTML data from the file- try:- from bs4 import BeautifulSoup- except ImportError:- raise ImportError(- "Please install `beautifulsoup4` first. "- "You can install it by running "- "`pip install beautifulsoup4`."- )+ from bs4 import BeautifulSoup+soup = BeautifulSoup(file, "html.parser")text = soup.get_text()text = strip_consecutive_newlines(text)diff --git a/camel/loaders/crawl4ai_reader.py b/camel/loaders/crawl4ai_reader.pyindex 622ed2162..5db8cffa2 100644--- a/camel/loaders/crawl4ai_reader.py+++ b/camel/loaders/crawl4ai_reader.py@@ -18,6 +18,8 @@ from typing import Any, Dict, List, Optional, Setfrom pydantic import BaseModel, ValidationError+from camel.utils import dependencies_required+logger = logging.getLogger(__name__)@@ -31,6 +33,7 @@ class Crawl4AI:https://docs.crawl4ai.com/"""+ @dependencies_required('crawl4ai')def __init__(self) -> None:from crawl4ai import AsyncWebCrawlerdiff --git a/camel/loaders/firecrawl_reader.py b/camel/loaders/firecrawl_reader.pyindex 4453b8618..4b1cf36b4 100644--- a/camel/loaders/firecrawl_reader.py+++ b/camel/loaders/firecrawl_reader.py@@ -17,6 +17,8 @@ from typing import Any, Dict, List, Optionalfrom pydantic import BaseModel+from camel.utils import dependencies_required+def _to_dict(response: Any) -> Any:r"""Normalize a Firecrawl SDK response into plain Python data.@@ -43,6 +45,7 @@ class Firecrawl:https://docs.firecrawl.dev/introduction"""+ @dependencies_required('firecrawl')def __init__(self,api_key: Optional[str] = None,diff --git a/camel/loaders/markitdown.py b/camel/loaders/markitdown.pyindex 7c4c2288b..44abcde35 100644--- a/camel/loaders/markitdown.py+++ b/camel/loaders/markitdown.py@@ -16,6 +16,7 @@ from concurrent.futures import ThreadPoolExecutor, as_completedfrom typing import ClassVar, Dict, List, Optionalfrom camel.logger import get_logger+from camel.utils import dependencies_requiredlogger = get_logger(__name__)@@ -66,6 +67,7 @@ class MarkItDownLoader:".md",]+ @dependencies_required('markitdown')def __init__(self,llm_client: Optional[object] = None,diff --git a/camel/loaders/scrapegraph_reader.py b/camel/loaders/scrapegraph_reader.pyindex 43d2b8104..f51309886 100644--- a/camel/loaders/scrapegraph_reader.py+++ b/camel/loaders/scrapegraph_reader.py@@ -15,6 +15,8 @@import osfrom typing import Any, Dict, Optional+from camel.utils import api_keys_required, dependencies_required+class ScrapeGraphAI:r"""ScrapeGraphAI allows you to perform AI-powered web scraping and@@ -28,6 +30,12 @@ class ScrapeGraphAI:https://scrapegraph.ai/"""+ @dependencies_required('scrapegraph_py')+ @api_keys_required(+ [+ ("api_key", "SCRAPEGRAPH_API_KEY"),+ ]+ )def __init__(self,api_key: Optional[str] = None,diff --git a/camel/loaders/unstructured_io.py b/camel/loaders/unstructured_io.pyindex 15dd1bb07..ff17737d2 100644--- a/camel/loaders/unstructured_io.py+++ b/camel/loaders/unstructured_io.py@@ -26,6 +26,8 @@ from typing import (Union,)+from camel.utils import dependencies_required+if TYPE_CHECKING:from unstructured.documents.elements import Element@@ -41,6 +43,7 @@ class UnstructuredIO:"""@staticmethod+ @dependencies_required('unstructured')def create_element_from_text(text: str,element_id: Optional[str] = None,@@ -94,6 +97,7 @@ class UnstructuredIO:)@staticmethod+ @dependencies_required('unstructured')def parse_file_or_url(input_path: str,**kwargs: Any,@@ -158,6 +162,7 @@ class UnstructuredIO:return []@staticmethod+ @dependencies_required('unstructured')def parse_bytes(file: IO[bytes], **kwargs: Any) -> List["Element"]:r"""Parses a bytes stream and converts its contents into elements.@@ -189,6 +194,7 @@ class UnstructuredIO:return []@staticmethod+ @dependencies_required('unstructured')def clean_text_data(text: str,clean_options: Optional[List[Tuple[str, Dict[str, Any]]]] = None,@@ -292,6 +298,7 @@ class UnstructuredIO:return cleaned_text@staticmethod+ @dependencies_required('unstructured')def extract_data_from_text(text: str,extract_type: Literal[@@ -358,6 +365,7 @@ class UnstructuredIO:return extraction_functions[extract_type](text, **kwargs)@staticmethod+ @dependencies_required('unstructured')def stage_elements(elements: List[Any],stage_type: Literal[@@ -442,6 +450,7 @@ class UnstructuredIO:return staging_functions[stage_type](elements, **kwargs)@staticmethod+ @dependencies_required('unstructured')def chunk_elements(elements: List["Element"], chunk_type: str, **kwargs) -> List["Element"]:diff --git a/test/loaders/test_loaders_decorators.py b/test/loaders/test_loaders_decorators.pynew file mode 100644index 000000000..beb15e3bd--- /dev/null+++ b/test/loaders/test_loaders_decorators.py@@ -0,0 +1,133 @@+# ========= Copyright 2023-2026 @ 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-2026 @ CAMEL-AI.org. All Rights Reserved. =========+"""+Test that the following decorators are correctly applied to camel.loaders:+@api_keys_required - should raise ValueError if value is missing+@dependencies_required - should raise ImportError if package/module is missing+"""++from io import BytesIO+from unittest.mock import patch++import pytest++fake_api_key = "fake_api_key"+++def _mock_missing(module_name: str):+ """Patch is_module_available to return False for a specific module."""+ original = __import__(+ 'camel.utils.commons', fromlist=['is_module_available']+ ).is_module_available++ def fake(m):+ if m == module_name:+ return False+ return original(m)++ return patch('camel.utils.commons.is_module_available', side_effect=fake)+++def test_crawl4ai_missing_dependency():+ from camel.loaders import Crawl4AI++ with _mock_missing('crawl4ai'):+ with pytest.raises(ImportError, match="crawl4ai"):+ Crawl4AI()+++def test_firecrawl_missing_dependency():+ from camel.loaders import Firecrawl++ with _mock_missing('firecrawl'):+ with pytest.raises(ImportError, match="firecrawl"):+ Firecrawl(api_key=fake_api_key)+++def test_markitdown_missing_dependency():+ from camel.loaders import MarkItDownLoader++ with _mock_missing('markitdown'):+ with pytest.raises(ImportError, match="markitdown"):+ MarkItDownLoader()+++def test_scrapegraph_missing_dependency():+ from camel.loaders import ScrapeGraphAI++ with _mock_missing('scrapegraph_py'):+ with pytest.raises(ImportError, match="scrapegraph_py"):+ ScrapeGraphAI(api_key=fake_api_key)+++def test_scrapegraph_missing_api_key():+ from camel.loaders import ScrapeGraphAI++ with patch('camel.utils.commons.is_module_available', return_value=True):+ with patch.dict('os.environ', {}, clear=True):+ with pytest.raises(ValueError, match="SCRAPEGRAPH_API_KEY"):+ ScrapeGraphAI()+++def test_base_io_missing_dependencies():+ from camel.loaders.base_io import HtmlFile, PdfFile++ with _mock_missing('fitz'):+ with pytest.raises(ImportError, match="fitz"):+ PdfFile.from_bytes(BytesIO(b"pdf"), "test.pdf")++ with _mock_missing('bs4'):+ with pytest.raises(ImportError, match="bs4"):+ HtmlFile.from_bytes(BytesIO(b"<html></html>"), "test.html")+++def test_unstructured_io_missing_dependency():+ from camel.loaders import UnstructuredIO++ with _mock_missing('unstructured'):+ with pytest.raises(ImportError, match="unstructured"):+ UnstructuredIO.create_element_from_text(text="test")++ with _mock_missing('unstructured'):+ with pytest.raises(ImportError, match="unstructured"):+ UnstructuredIO.parse_file_or_url(input_path="test.txt")++ with _mock_missing('unstructured'):+ with pytest.raises(ImportError, match="unstructured"):+ UnstructuredIO.parse_bytes(file=BytesIO(b"test"))++ with _mock_missing('unstructured'):+ with pytest.raises(ImportError, match="unstructured"):+ UnstructuredIO.clean_text_data(text="test")++ with _mock_missing('unstructured'):+ with pytest.raises(ImportError, match="unstructured"):+ UnstructuredIO.extract_data_from_text(+ text="[email protected]",+ extract_type="extract_email_address",+ )++ with _mock_missing('unstructured'):+ with pytest.raises(ImportError, match="unstructured"):+ UnstructuredIO.stage_elements(+ elements=[],+ stage_type="convert_to_dict",+ )++ with _mock_missing('unstructured'):+ with pytest.raises(ImportError, match="unstructured"):+ UnstructuredIO.chunk_elements(+ elements=[],+ chunk_type="chunk_by_title",+ )