🐫 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] Allow for a dict of strings to be the input for the step function (#2093)
Apokryphosx094a3626dc78
diff --git a/camel/environments/single_step.py b/camel/environments/single_step.pyindex c5ed5729d..3e7d65cb4 100644--- a/camel/environments/single_step.py+++ b/camel/environments/single_step.py@@ -224,7 +224,7 @@ class SingleStepEnv:raise TypeError(f"Unsupported dataset type: {type(self.dataset)}")async def step(- self, action: Union[Action, List[Action], str]+ self, action: Union[Action, List[Action], str, Dict[int, str]]) -> Union[Tuple[Observation, float, bool, Dict[str, Any]],List[Tuple[Observation, float, bool, Dict[str, Any]]],@@ -242,13 +242,15 @@ class SingleStepEnv:the observation will not change.Args:- action (Union[Action, List[Action], str]):+ action (Union[Action, List[Action], str, Dict[int, str]]):The action(s) taken by the agent,which should contain the response(s)to the observation(s). Can be:- A single `Action` object (for batch size 1),- A list of `Action` objects (for batched evaluation),- A raw string (only allowed when batch size is 1).+ - A dict that maps indices to their `llm_response`+ (for batched evaluation)Returns:Union[Tuple[Observation, float, bool, Dict[str, Any]], List[...]]:@@ -293,6 +295,7 @@ class SingleStepEnv:f"total batch size ({self.current_batch_size})")+ indices = [act.index for act in actions]proposed_solutions = [act.llm_response for act in actions]ground_truths: List[str] = []for idx in indices:@@ -334,21 +337,22 @@ class SingleStepEnv:).as_tuple()for i in range(len(actions))]+for _, idx in enumerate(indices):self._states_done[idx] = Truereturn step_results[0] if len(step_results) == 1 else step_resultsdef _normalize_actions(- self, action: Union[Action, List[Action], str]+ self, action: Union[Action, List[Action], str, Dict[int, str]]) -> List[Action]:r"""Normalize the user-provided action(s) into a validated listof `Action` objects.This method handles flexibility in input format by converting- raw strings (only allowed when batch size is 1) and ensuring- all necessary structure and integrity checks on actions- (e.g., index bounds, duplicates).+ raw strings (only allowed when batch size is 1) and dictionaries,+ ensuring all necessary structure and integrity checks on+ actions (e.g., index bounds, duplicates).Args:action (Union[Action, List[Action], str]):@@ -357,6 +361,7 @@ class SingleStepEnv:- A list of `Action` objects.- A raw string (if `batch_size == 1`), auto-wrappedin an `Action`.+ - A dict mapping int indices to str responsesReturns:List[Action]: A list of validated `Action` instances@@ -368,8 +373,9 @@ class SingleStepEnv:- Action list is empty,- Index mismatches expected values(e.g., 0 for batch size 1),- - Wrong structure is used- (e.g., string used with batch size > 1).+ - Wrong structure is used (e.g.,+ string used with batch size > 1,+ dict used with batch size == 1).TypeError: If the action is of an unsupported type."""@@ -380,9 +386,20 @@ class SingleStepEnv:" when batch_size == 1")logger.warning("Auto-converting from str to Action", stacklevel=2)- action = Action(index=0, llm_response=action)+ actions = [Action(index=0, llm_response=action)]++ elif isinstance(action, dict):+ if not all(isinstance(k, int) for k in action.keys()):+ raise ValueError("All dictionary keys must be integers")- if isinstance(action, Action):+ if self.current_batch_size == 1 and list(action.keys()) != [0]:+ raise ValueError(+ "For batch_size=1, dict input must have exactly one key: 0"+ )+ actions = [+ Action(index=k, llm_response=v) for k, v in action.items()+ ]+ elif isinstance(action, Action):actions = [action]elif isinstance(action, list):if not action:@@ -397,7 +414,7 @@ class SingleStepEnv:if self.current_batch_size == 1 and len(actions) != 1:raise ValueError(- "For batch_size=1, expect a single Action or a "+ "For batch_size=1, expect a single Action, a dictionary or a ""list containing exactly one Action")diff --git a/test/environments/test_single_step_env.py b/test/environments/test_single_step_env.pyindex 1882d0fda..149ae3114 100644--- a/test/environments/test_single_step_env.py+++ b/test/environments/test_single_step_env.py@@ -586,8 +586,8 @@ async def test_single_step_env_error_handling_single():# b) Providing a list of 2 actions for batch size == 1with pytest.raises(ValueError,- match="For batch_size=1, expect a single Action or a list containing "- "exactly one Action",+ match="For batch_size=1, expect a single Action, a dictionary or "+ "a list containing exactly one Action",):await env_invalid_actions.step([@@ -863,3 +863,150 @@ async def test_batched_single_step_env_error_handling():await env_close_fail.setup()with pytest.raises(Exception, match="Cleanup failed"):await env_close_fail.close()+++async def test_single_step_env_all_input_types():+ # Define a simple dataset+ data = [+ {+ "question": "What is 2 + 2?",+ "final_answer": "4",+ "rationale": "Adding 2 and 2 gives 4.",+ "metadata": {"difficulty": "easy"},+ },+ {+ "question": "What is the capital of France?",+ "final_answer": "Paris",+ "rationale": "Paris is known as the capital city of France.",+ "metadata": {"difficulty": "easy"},+ },+ ]+ dataset = StaticDataset(data)++ # Create a mock verifier+ mock_verifier = MagicMock()+ mock_verifier.setup = AsyncMock()+ mock_verifier.cleanup = AsyncMock()+ mock_verifier.verify_batch = AsyncMock(+ side_effect=lambda solutions, reference_answers, **kwargs: [+ VerificationResult(+ status=VerificationOutcome.SUCCESS,+ result="Verification successful",+ feedback="Correct",+ score=1.0,+ )+ for _ in solutions+ ]+ )++ # Initialize the environment+ env = SingleStepEnv(dataset=dataset, verifier=mock_verifier)+ await env.setup()++ # --- Test with batch_size=1 ---+ await env.reset(batch_size=1)++ # 1. Test str input (valid for batch_size=1)+ result = await env.step("4")+ assert isinstance(result, tuple)+ _, reward, done, _ = result+ assert reward == env.ACCURACY_REWARD+ assert done is True++ # Reset for next test+ await env.reset(batch_size=1)++ # 2. Test Action input (valid)+ result = await env.step(Action(index=0, llm_response="4"))+ assert isinstance(result, tuple)+ _, reward, done, _ = result+ assert reward == env.ACCURACY_REWARD+ assert done is True++ # Reset for next test+ await env.reset(batch_size=1)++ # 3. Test List[Action] input (valid with one element)+ result = await env.step([Action(index=0, llm_response="4")])+ assert isinstance(result, tuple)+ _, reward, done, _ = result+ assert reward == env.ACCURACY_REWARD+ assert done is True++ # Reset for error tests+ await env.reset(batch_size=1)++ # 4. Test List[Action] with too many elements+ with pytest.raises(+ ValueError,+ match="For batch_size=1, expect a single Action, a dictionary or "+ "a list containing exactly one Action",+ ):+ await env.step(+ [+ Action(index=0, llm_response="4"),+ Action(index=1, llm_response="Paris"),+ ]+ )++ # 5. Test Action with wrong index+ with pytest.raises(+ ValueError, match="For batch_size=1, Action index must be 0"+ ):+ await env.step(Action(index=1, llm_response="4"))++ # --- Test with batch_size=2 ---+ await env.reset(batch_size=2)++ # 6. Test Dict[int, str] input (valid for batch_size > 1)+ result = await env.step({0: "4", 1: "Paris"})+ assert isinstance(result, list)+ assert len(result) == 2+ for _, reward, done, _ in result:+ assert reward == env.ACCURACY_REWARD+ assert done is True++ # Reset for next test+ await env.reset(batch_size=2)++ # 7. Test List[Action] input (valid)+ result = await env.step(+ [+ Action(index=0, llm_response="4"),+ Action(index=1, llm_response="Paris"),+ ]+ )+ assert isinstance(result, list)+ assert len(result) == 2+ for _, reward, done, _ in result:+ assert reward == env.ACCURACY_REWARD+ assert done is True++ # Reset for next test+ await env.reset(batch_size=2)++ # 8. Test str with batch_size > 1 (should fail)+ with pytest.raises(+ ValueError,+ match="String input for action is only allowed when batch_size == 1",+ ):+ await env.step("4")++ # 9. Test Dict[int, str] with non-integer keys+ with pytest.raises(+ ValueError, match="All dictionary keys must be integers"+ ):+ await env.step({"0": "4", 1: "Paris"})++ # 10. Test List[Action] with non-Action elements+ with pytest.raises(+ ValueError, match="All elements in the list must be Action objects"+ ):+ await env.step([Action(index=0, llm_response="4"), "Paris"])++ # 11. Test invalid index in List[Action]+ with pytest.raises(ValueError, match="Invalid state index 2"):+ await env.step([Action(index=2, llm_response="4")])++ await env.close()