🐫 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: Implement extraction as strategy pattern (#1742)
hallerite83b7c322f95d
diff --git a/camel/environments/base.py b/camel/environments/base.pyindex 9b187d88a..61530d24b 100644--- a/camel/environments/base.py+++ b/camel/environments/base.py@@ -151,20 +151,26 @@ class BaseEnvironment(ABC):r"""Initialize the environment.Args:- dataset: Dataset to sample questions from.- verifier: Verifier to check responses.- extractor: Extractor to process LLM responses.- max_steps: Maximum steps per episode.- teacher_agent: Optional agent for reward shaping and hints- curriculum_config: Configuration for curriculum learning including:+ dataset (BaseDataset): Dataset to sample questions from.+ verifier (BaseVerifier): Verifier to check responses.+ extractor (BaseExtractor): Extractor to process LLM responses.+ max_steps (Optional[int]): Maximum steps per episode. (default:+ :obj:`None`)+ teacher_agent (Optional[ChatAgent]): Optional agent for reward+ shaping and hints. (default: :obj:`None`)+ curriculum_config (Optional[Dict[str, Any]]): Configuration for+ curriculum learning including:- difficulty_levels: List of available difficulty levels- promotion_threshold: Score needed to advance- demotion_threshold: Score triggering level decrease- min_questions_per_level: Questions before promotion- practice_env_config: Configuration for practice environments:+ (default: :obj:`None`)+ practice_env_config (Optional[Dict[str, Any]]): Configuration for+ practice environments:- max_practice_envs: Maximum concurrent environments- difficulty_range: Allowed difficulty variation- focus_areas: Specific skills to practice+ (default: :obj:`None`)**kwargs: Additional environment parameters."""self.dataset = dataset@@ -289,7 +295,9 @@ class BaseEnvironment(ABC):# extract verifiable part from llm responseextraction_result = await self.extractor.extract(action.llm_response)- # TODO: extract executable llm response specifically+ # Ensure extraction_result is a string+ if extraction_result is None:+ extraction_result = ""# verify the extractedverification_result = await self.verifier.verify(diff --git a/camel/extractors/__init__.py b/camel/extractors/__init__.pyindex 2f77f0480..51ab870ac 100644--- a/camel/extractors/__init__.py+++ b/camel/extractors/__init__.py@@ -11,6 +11,6 @@# See the License for the specific language governing permissions and# limitations under the License.# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========-from .base import BaseExtractor+from .base import BaseExtractor, BaseExtractorStrategy-__all__ = ["BaseExtractor"]+__all__ = ["BaseExtractor", "BaseExtractorStrategy"]diff --git a/camel/extractors/base.py b/camel/extractors/base.pyindex b9e076358..df57e5fbb 100644--- a/camel/extractors/base.py+++ b/camel/extractors/base.py@@ -12,11 +12,10 @@# limitations under the License.# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========+import asynciofrom abc import ABC, abstractmethodfrom types import TracebackType-from typing import Any, Dict, Optional, Type--from typing_extensions import Self+from typing import Any, Dict, List, Optional, Typefrom camel.logger import get_loggerfrom camel.utils import BatchProcessor@@ -24,16 +23,36 @@ from camel.utils import BatchProcessorlogger = get_logger(__name__)-class BaseExtractor(ABC):- r"""Base class for all response extractors.+class BaseExtractorStrategy(ABC):+ r"""Abstract base class for extraction strategies."""++ @abstractmethod+ async def extract(self, text: str) -> Optional[str]:+ r"""Asynchronously extracts relevant parts from text.++ Args:+ text (str): The input text to process.++ Returns:+ Optional[str]: Extracted str if successful, otherwise None.+ """+ pass+++class BaseExtractor:+ r"""Base class for response extractors with a fixed strategy pipeline.- An extractor takes the response and extracts the relevant parts,- converting them into a format that the verifier can handle.- Implements async context manager protocol for proper resource management.+ This extractor:+ - Uses a **fixed multi-stage pipeline** of extraction strategies.+ - Tries **each strategy in order** within a stage until one succeeds.+ - Feeds the **output of one stage into the next** for processing.+ - Supports **async execution** for efficient processing.+ - Provides **batch processing and resource monitoring** options."""def __init__(self,+ pipeline: List[List[BaseExtractorStrategy]],cache_templates: bool = True,max_cache_size: int = 1000,extraction_timeout: float = 30.0,@@ -43,9 +62,12 @@ class BaseExtractor(ABC):memory_threshold: float = 85.0,**kwargs,):- r"""Initialize the extractor.+ r"""Initialize the extractor with a multi-stage strategy pipeline.Args:+ pipeline (List[List[BaseExtractorStrategy]]):+ A fixed list of lists where each list represents a stage+ containing extractor strategies executed in order.cache_templates (bool): Whether to cache extraction templates.(default: :obj:`True`)max_cache_size (int): Maximum number of templates to cache.@@ -61,11 +83,8 @@ class BaseExtractor(ABC):memory_threshold (float): Memory usage percentage threshold forscaling down. (default: :obj:`85.0`)**kwargs: Additional extractor parameters.-- Raises:- ValueError: If invalid parameter values are provided"""- # Store all parameters in metadata dict for compatibility+self._metadata = {'cache_templates': cache_templates,'max_cache_size': max_cache_size,@@ -81,14 +100,7 @@ class BaseExtractor(ABC):self._cache: Dict[str, Any] = {}self._batch_processor: Optional[BatchProcessor] = None- # Store configuration parameters- self._cache_templates = cache_templates- self._max_cache_size = max_cache_size- self._extraction_timeout = extraction_timeout- self._batch_size = batch_size- self._monitoring_interval = monitoring_interval- self._cpu_threshold = cpu_threshold- self._memory_threshold = memory_threshold+ self._pipeline = pipelineasync def setup(self) -> None:r"""Set up the extractor with necessary resources.@@ -106,17 +118,15 @@ class BaseExtractor(ABC):returntry:- # Initialize template cache if enabled- if self._cache_templates:+ if self._metadata["cache_templates"]:self._template_cache: Dict[str, Any] = {}- # Set up batch processing if needed- if self._batch_size > 1:+ if self._metadata["batch_size"] > 1:self._batch_processor = BatchProcessor(- initial_batch_size=self._batch_size,- monitoring_interval=self._monitoring_interval,- cpu_threshold=self._cpu_threshold,- memory_threshold=self._memory_threshold,+ initial_batch_size=self._metadata["batch_size"],+ monitoring_interval=self._metadata["monitoring_interval"],+ cpu_threshold=self._metadata["cpu_threshold"],+ memory_threshold=self._metadata["memory_threshold"],)self._is_setup = True@@ -171,13 +181,6 @@ class BaseExtractor(ABC):)# Preserve init config in metadata- self._metadata = {- 'cache_templates': self._cache_templates,- 'max_cache_size': self._max_cache_size,- 'extraction_timeout': self._extraction_timeout,- 'batch_size': self._batch_size,- }-if not errors:logger.info(f"{self.__class__.__name__} cleaned up successfully"@@ -187,23 +190,19 @@ class BaseExtractor(ABC):errors.append(f"Unexpected error during cleanup: {e}")finally:- # Always mark as uninitialized, even if cleanup failsself._is_setup = Falseself._batch_processor = Noneif errors:- error_msg = (- f"Errors during {self.__class__.__name__} cleanup: "- f"{'; '.join(errors)}"- )+ error_msg = f"Errors during cleanup: {'; '.join(errors)}"logger.error(error_msg)raise RuntimeError(error_msg)- async def __aenter__(self) -> Self:+ async def __aenter__(self) -> "BaseExtractor":r"""Async context manager entry.Returns:- Self reference for context manager usage.+ BaseExtractor: The initialized extractor instance."""await self.setup()return self@@ -226,38 +225,61 @@ class BaseExtractor(ABC):"""await self.cleanup()- @abstractmethod- async def extract(- self, response: str, context: Optional[Dict[str, Any]] = None- ) -> str:- r"""Extract relevant parts from a response.-- Extracts:- 1. Final answer or output- 2. Chain of thought reasoning steps- 3. Difficulty assessment+ async def extract(self, response: str) -> Optional[str]:+ r"""Extracts a normalized, comparable part of the LLM response+ using the fixed multi-stage strategy pipeline.Args:- response (str): Raw response from agent generation.- context (Optional[Dict[str, Any]]): Optional context for- extraction like:- - final_answer- - rationale- - complexity+ response (str): The raw response text.Returns:- str: Extracted content string.+ Optional[str]: Extracted data if successful, otherwise None.Raises:ValueError: If response is empty or invalid.- NotImplementedError: If no implementation is provided.RuntimeError: If extractor is not initialized."""if not self._is_setup:raise RuntimeError(- f"{self.__class__.__name__} must be initialized "- "before extraction"+ "Extractor must be initialized before extraction")if not response or not response.strip():raise ValueError("Empty or whitespace-only response")- raise NotImplementedError("Subclasses must implement extract()")++ current_input = response # Initial input++ for stage in self._pipeline:+ stage_success = (+ False # Track if any strategy in the stage succeeds+ )++ for strategy in stage:+ try:+ # Apply the extraction timeout+ result = await asyncio.wait_for(+ strategy.extract(current_input),+ timeout=self._metadata["extraction_timeout"],+ )++ if result is not None:+ current_input = result # Feed into next stage+ stage_success = True+ break # Move to next stage if valid extraction occurs++ except asyncio.TimeoutError:+ logger.warning(+ f"Strategy {strategy.__class__.__name__} timed out "+ f"after {self._metadata['extraction_timeout']} seconds"+ )+ except Exception as e:+ logger.warning(+ f"Strategy {strategy.__class__.__name__} failed: {e}"+ )++ if not stage_success:+ logger.debug(+ "No strategy in stage succeeded, stopping extraction."+ )+ return None # Stop processing if the stage fails++ return current_input # Final processed outputdiff --git a/camel/extractors/python_strategies.py b/camel/extractors/python_strategies.pynew file mode 100644index 000000000..25f4531f7--- /dev/null+++ b/camel/extractors/python_strategies.py@@ -0,0 +1,226 @@+# ========= Copyright 2023-2024 @ 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-2024 @ CAMEL-AI.org. All Rights Reserved. =========++import ast+from typing import Optional++from camel.extractors.base import BaseExtractorStrategy+from camel.logger import get_logger++logger = get_logger(__name__)+++class BoxedStrategy(BaseExtractorStrategy):+ r"""Extracts content from \\boxed{} environments."""++ async def extract(self, text: str) -> Optional[str]:+ r"""Extract content from \\boxed{} environments.++ Args:+ text (str): The input text to process.++ Returns:+ Optional[str]: Content inside \\boxed{} if found, else None.+ """+ # Find the start of the boxed content+ boxed_pattern = "\\boxed{"+ if boxed_pattern not in text:+ logger.debug("No \\boxed{} content found in the response")+ return None++ start_idx = text.find(boxed_pattern) + len(boxed_pattern)+ if start_idx >= len(text):+ logger.debug("Malformed \\boxed{} (no content after opening)")+ return None++ # Use stack-based approach to handle nested braces+ stack = 1 # Start with one opening brace+ end_idx = start_idx+ escape_mode = False++ for i in range(start_idx, len(text)):+ char = text[i]++ # Handle escape sequences+ if escape_mode:+ escape_mode = False+ continue++ if char == '\\':+ escape_mode = True+ continue++ if char == '{':+ stack += 1+ elif char == '}':+ stack -= 1++ if stack == 0: # Found the matching closing brace+ end_idx = i+ break++ # Check if we found a complete boxed expression+ if stack != 0:+ logger.debug("Unbalanced braces in \\boxed{} content")+ return None++ # Extract the content+ content = text[start_idx:end_idx].strip()+ logger.debug(f"Extracted boxed content: {content}")+ return content+++class PythonListStrategy(BaseExtractorStrategy):+ r"""Extracts and normalizes Python lists."""++ async def extract(self, text: str) -> Optional[str]:+ r"""Extract and normalize a Python list.++ Args:+ text (str): The input text to process.++ Returns:+ Optional[str]: Normalized list as a string if found, else None.+ """++ text = text.strip()+ if not (text.startswith('[') and text.endswith(']')):+ logger.debug("Content is not a list format (missing brackets)")+ return None++ try:+ # Fix any escaped quotes before parsing+ fixed_content = text.replace('\\"', '"')+ parsed = ast.literal_eval(fixed_content)+ if isinstance(parsed, list):+ # Sort the list for normalization+ sorted_list = sorted(parsed, key=lambda x: str(x))+ return repr(sorted_list)+ else:+ logger.debug(f"Content is not a list, got {type(parsed)}")+ return None+ except (SyntaxError, ValueError) as e:+ logger.debug(f"Failed to parse as Python list: {e}")+ return None+++class PythonDictStrategy(BaseExtractorStrategy):+ r"""Extracts and normalizes Python dictionaries."""++ async def extract(self, text: str) -> Optional[str]:+ r"""Extract and normalize a Python dictionary.++ Args:+ text (str): The input text to process.++ Returns:+ Optional[str]: Normalized dictionary as a string, else None.+ """++ text = text.strip()+ if not (text.startswith('{') and text.endswith('}')):+ logger.debug("Content is not a dictionary format (missing braces)")+ return None++ try:+ # Fix any escaped quotes before parsing+ fixed_content = text.replace('\\"', '"')+ parsed = ast.literal_eval(fixed_content)+ if isinstance(parsed, dict):+ # Sort the dictionary items for normalization+ sorted_dict = dict(+ sorted(parsed.items(), key=lambda x: str(x[0]))+ )+ return repr(sorted_dict)+ else:+ logger.debug(+ f"Content is not a dictionary, got {type(parsed)}"+ )+ return None+ except (SyntaxError, ValueError) as e:+ logger.debug(f"Failed to parse as Python dictionary: {e}")+ return None+++class PythonSetStrategy(BaseExtractorStrategy):+ r"""Extracts and normalizes Python sets."""++ async def extract(self, text: str) -> Optional[str]:+ r"""Extract and normalize a Python set.++ Args:+ text (str): The input text to process.++ Returns:+ Optional[str]: Normalized set as a string if found, else None.+ """++ text = text.strip()+ # Check for set syntax: {1, 2, 3} or set([1, 2, 3])+ if not (+ (text.startswith('{') and text.endswith('}'))+ or (text.startswith('set(') and text.endswith(')'))+ ):+ logger.debug("Content is not a set format")+ return None++ try:+ # Fix any escaped quotes before parsing+ fixed_content = text.replace('\\"', '"')+ parsed = ast.literal_eval(fixed_content)+ if isinstance(parsed, set):+ # Sort the set elements for normalization+ sorted_set = sorted(parsed, key=lambda x: str(x))+ return repr(set(sorted_set))+ else:+ logger.debug(f"Content is not a set, got {type(parsed)}")+ return None+ except (SyntaxError, ValueError) as e:+ logger.debug(f"Failed to parse as Python set: {e}")+ return None+++class PythonTupleStrategy(BaseExtractorStrategy):+ r"""Extracts and normalizes Python tuples."""++ async def extract(self, text: str) -> Optional[str]:+ r"""Extract and normalize a Python tuple.++ Args:+ text (str): The input text to process.++ Returns:+ Optional[str]: Normalized tuple as a string if found, else None.+ """++ text = text.strip()+ # Check for tuple syntax: (1, 2, 3) or (1,)+ if not (text.startswith('(') and text.endswith(')')):+ logger.debug("Content is not a tuple format (missing parentheses)")+ return None++ try:+ # Fix any escaped quotes before parsing+ fixed_content = text.replace('\\"', '"')+ parsed = ast.literal_eval(fixed_content)+ if isinstance(parsed, tuple):+ # Sort the tuple elements for normalization+ sorted_tuple = tuple(sorted(parsed, key=lambda x: str(x)))+ return repr(sorted_tuple)+ else:+ logger.debug(f"Content is not a tuple, got {type(parsed)}")+ return None+ except (SyntaxError, ValueError) as e:+ logger.debug(f"Failed to parse as Python tuple: {e}")+ return Nonediff --git a/examples/extractors/python_strategies_example.py b/examples/extractors/python_strategies_example.pynew file mode 100644index 000000000..08bac4eef--- /dev/null+++ b/examples/extractors/python_strategies_example.py@@ -0,0 +1,179 @@+# ========= Copyright 2023-2024 @ 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-2024 @ CAMEL-AI.org. All Rights Reserved. =========+import ast+import asyncio++from camel.extractors.base import BaseExtractor+from camel.extractors.python_strategies import (+ BoxedStrategy,+ PythonDictStrategy,+ PythonListStrategy,+)+from camel.logger import get_logger++logger = get_logger(__name__)+++def create_list_extractor(+ _cache_templates=True,+ max_cache_size=5000,+ extraction_timeout=60.0,+ _batch_size=20,+ _monitoring_interval=10.0,+ _cpu_threshold=90.0,+ _memory_threshold=90.0,+) -> "BaseExtractor":+ r"""Create an extractor for Python lists."""+ # Create a pipeline with two stages+ pipeline = [+ [BoxedStrategy()], # Stage 1: Extract boxed content+ [PythonListStrategy()], # Stage 2: Extract and normalize Python list+ ]++ return BaseExtractor(+ pipeline=pipeline,+ cache_templates=_cache_templates,+ max_cache_size=max_cache_size,+ extraction_timeout=extraction_timeout,+ batch_size=_batch_size,+ monitoring_interval=_monitoring_interval,+ cpu_threshold=_cpu_threshold,+ memory_threshold=_memory_threshold,+ default_value="[]",+ )+++def create_dict_extractor(+ _cache_templates=True,+ max_cache_size=5000,+ extraction_timeout=60.0,+ _batch_size=20,+ _monitoring_interval=10.0,+ _cpu_threshold=90.0,+ _memory_threshold=90.0,+) -> "BaseExtractor":+ r"""Create an extractor for Python dictionaries."""+ # Create a pipeline with two stages+ pipeline = [+ [BoxedStrategy()], # Stage 1: Extract boxed content+ [PythonDictStrategy()], # Stage 2: Extract and normalize Python dict+ ]++ return BaseExtractor(+ pipeline=pipeline,+ cache_templates=_cache_templates,+ max_cache_size=max_cache_size,+ extraction_timeout=extraction_timeout,+ batch_size=_batch_size,+ monitoring_interval=_monitoring_interval,+ cpu_threshold=_cpu_threshold,+ memory_threshold=_memory_threshold,+ default_value="{}",+ )+++async def example_list_extraction():+ r"""Demonstrate list extraction."""+ print("\n=== Example 1: List extraction ===")++ # Example LLM response with a list in \boxed{} format+ llm_response = r"\boxed{[3, 1, 2, 'apple']}"++ # Create a list extractor+ extractor = create_list_extractor()++ # Set up the extractor+ await extractor.setup()++ try:+ # Extract the list+ result = await extractor.extract(llm_response)++ print(f"LLM Response: {llm_response}")+ print(f"Extracted list string: {result}")++ # Parse the result to get the actual list+ try:+ parsed_list = ast.literal_eval(result)+ print(f"Parsed list: {parsed_list}")+ except (SyntaxError, ValueError) as e:+ print(f"Error parsing result: {e}")++ finally:+ # Clean up the extractor+ await extractor.cleanup()+++async def example_dict_extraction():+ r"""Demonstrate dictionary extraction."""+ print("\n=== Example 2: Dictionary extraction ===")++ # Example LLM response with a dictionary in \boxed{} format+ llm_response = r"\boxed{{'apple': 5, 'banana': 3, 'cherry': 8}}"++ # Create a dictionary extractor+ extractor = create_dict_extractor()++ # Set up the extractor+ await extractor.setup()++ try:+ # Extract the dictionary+ result = await extractor.extract(llm_response)++ print(f"LLM Response: {llm_response}")+ print(f"Extracted dictionary string: {result}")++ # Parse the result to get the actual dictionary+ try:+ parsed_dict = ast.literal_eval(result)+ print(f"Parsed dictionary: {parsed_dict}")+ except (SyntaxError, ValueError) as e:+ print(f"Error parsing result: {e}")++ finally:+ # Clean up the extractor+ await extractor.cleanup()+++async def main():+ r"""Run all examples."""+ print("=== Python Strategies Examples ===")++ await example_list_extraction()+ await example_dict_extraction()++ print("\nAll examples completed.")+++if __name__ == "__main__":+ asyncio.run(main())++"""+===============================================================================+=== Python Strategies Examples ===++=== Example 1: List extraction ===+LLM Response: \boxed{[3, 1, 2, 'apple']}+Extracted list string: [1, 2, 3, 'apple']+Parsed list: [1, 2, 3, 'apple']++=== Example 2: Dictionary extraction ===+LLM Response: \boxed{{'apple': 5, 'banana': 3, 'cherry': 8}}+Extracted dictionary string: {'apple': 5, 'banana': 3, 'cherry': 8}+Parsed dictionary: {'apple': 5, 'banana': 3, 'cherry': 8}++All examples completed.+===============================================================================+"""diff --git a/pyproject.toml b/pyproject.tomlindex 5e5d657d0..bbade0332 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -451,6 +451,7 @@ module = ["tabulate","openpyxl","scenedetect",+ "scenedetect.detectors","playwright","html2text","docx",diff --git a/test/extractors/test_base_extractor.py b/test/extractors/test_base_extractor.pyindex df238362a..3d08f5545 100644--- a/test/extractors/test_base_extractor.py+++ b/test/extractors/test_base_extractor.py@@ -12,17 +12,42 @@# limitations under the License.# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========-from typing import Any, Dict, Optional+from typing import Any, Dict, List, Optionalfrom unittest.mock import MagicMockimport pytest-from camel.extractors.base import BaseExtractor+from camel.extractors.base import BaseExtractor, BaseExtractorStrategy+++class DummyStrategy(BaseExtractorStrategy):+ r"""A dummy strategy that just returns the input text."""++ async def extract(self, text: str) -> Optional[str]:+ return textclass TestExtractor(BaseExtractor):r"""Concrete implementation of BaseExtractor for testing."""+ def __init__(+ self,+ cache_templates: bool = True,+ max_cache_size: int = 1000,+ extraction_timeout: float = 30.0,+ batch_size: int = 10,+ **kwargs,+ ):+ pipeline: List[List[BaseExtractorStrategy]] = [[DummyStrategy()]]+ super().__init__(+ pipeline=pipeline,+ cache_templates=cache_templates,+ max_cache_size=max_cache_size,+ extraction_timeout=extraction_timeout,+ batch_size=batch_size,+ **kwargs,+ )+async def extract(self, response: str, context: Optional[Dict[str, Any]] = None) -> str:@@ -59,10 +84,10 @@ def test_extractor_init():batch_size=20,custom_param="value",)- assert extractor._cache_templates is False- assert extractor._max_cache_size == 500- assert extractor._extraction_timeout == 15.0- assert extractor._batch_size == 20+ assert extractor._metadata["cache_templates"] is False+ assert extractor._metadata["max_cache_size"] == 500+ assert extractor._metadata["extraction_timeout"] == 15.0+ assert extractor._metadata["batch_size"] == 20assert extractor._metadata["custom_param"] == "value"diff --git a/test/extractors/test_python_strategies.py b/test/extractors/test_python_strategies.pynew file mode 100644index 000000000..8138cad61--- /dev/null+++ b/test/extractors/test_python_strategies.py@@ -0,0 +1,149 @@+# ========= Copyright 2023-2024 @ 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-2024 @ CAMEL-AI.org. All Rights Reserved. =========+import pytest++from camel.extractors.python_strategies import (+ BoxedStrategy,+ PythonDictStrategy,+ PythonListStrategy,+ PythonSetStrategy,+ PythonTupleStrategy,+)+++async def test_boxed_strategy():+ strategy = BoxedStrategy()++ # Test basic boxed content+ text = r"\boxed{test content}"+ result = await strategy.extract(text)+ assert result == "test content"++ # Test nested braces+ text = r"\boxed{nested {braces} test}"+ result = await strategy.extract(text)+ assert result == "nested {braces} test"++ # Test escaped characters+ text = r"\boxed{content with \{ escaped \} braces}"+ result = await strategy.extract(text)+ assert result == r"content with \{ escaped \} braces"++ # Test invalid cases+ assert await strategy.extract("no boxed content") is None+ assert await strategy.extract(r"\boxed{unclosed") is None+ assert await strategy.extract(r"\boxed{}") == ""+++async def test_python_list_strategy():+ strategy = PythonListStrategy()++ # Test basic list+ text = "[1, 2, 3]"+ result = await strategy.extract(text)+ assert result == "[1, 2, 3]"++ # Test list with mixed types+ text = '[1, "two", 3.0]'+ result = await strategy.extract(text)+ expected_list = sorted([1, "two", 3.0], key=lambda x: str(x))+ assert result == repr(expected_list)++ # Test nested list+ text = '[[1, 2], [3, 4]]'+ result = await strategy.extract(text)+ assert result == "[[1, 2], [3, 4]]"++ # Test invalid cases+ assert await strategy.extract("not a list") is None+ assert await strategy.extract("[invalid") is None+ result = await strategy.extract("[1, 2,]")+ assert result == "[1, 2]"+++async def test_python_dict_strategy():+ strategy = PythonDictStrategy()++ # Test basic dict+ text = '{"a": 1, "b": 2}'+ result = await strategy.extract(text)+ assert result == "{'a': 1, 'b': 2}"++ # Test mixed type values+ text = '{"b": [1, 2], "a": "string"}'+ result = await strategy.extract(text)+ input_dict = {"b": [1, 2], "a": "string"}+ sorted_dict = dict(sorted(input_dict.items(), key=lambda x: str(x[0])))+ assert result == repr(sorted_dict)++ # Test nested dict+ text = '{"outer": {"inner": 1}}'+ result = await strategy.extract(text)+ assert result == "{'outer': {'inner': 1}}"++ # Test invalid cases+ assert await strategy.extract("not a dict") is None+ assert await strategy.extract("{invalid}") is None+ assert await strategy.extract('{"key": value}') is None+++async def test_python_set_strategy():+ strategy = PythonSetStrategy()++ # Test basic set+ text = '{1, 2, 3}'+ result = await strategy.extract(text)+ assert result == "{1, 2, 3}"++ # Test set with mixed types+ text = '{1, "two", 3.0}'+ result = await strategy.extract(text)+ input_set = {1, "two", 3.0}+ sorted_elements = sorted(input_set, key=lambda x: str(x))+ assert result == repr(set(sorted_elements))++ # Test invalid cases+ assert await strategy.extract("not a set") is None+ assert await strategy.extract("{invalid") is None+ assert await strategy.extract("set(invalid)") is None+++async def test_python_tuple_strategy():+ strategy = PythonTupleStrategy()++ # Test basic tuple+ text = '(1, 2, 3)'+ result = await strategy.extract(text)+ assert result == '(1, 2, 3)'++ # Test tuple with mixed types+ text = '(1, "two", 3.0)'+ result = await strategy.extract(text)+ input_tuple = (1, "two", 3.0)+ sorted_tuple = tuple(sorted(input_tuple, key=lambda x: str(x)))+ assert result == repr(sorted_tuple)++ # Test nested tuple+ text = '((1, 2), (3, 4))'+ result = await strategy.extract(text)+ assert result == "((1, 2), (3, 4))"++ # Test invalid cases+ assert await strategy.extract("not a tuple") is None+ assert await strategy.extract("(invalid)") is None