🐫 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
fix within_timeout error catching bug (#3365)
Qijia Shen5f188c1e1e98
diff --git a/camel/utils/commons.py b/camel/utils/commons.pyindex 63737243d..ca7022286 100644--- a/camel/utils/commons.py+++ b/camel/utils/commons.py@@ -1028,14 +1028,19 @@ def with_timeout(timeout=None):if loop_running:return func(*args, **kwargs)- # Container to hold the result of the function call+ # Container to hold the result or exception from the function+ # callresult_container = []+ exception_container = []def target():- result_container.append(func(*args, **kwargs))+ try:+ result_container.append(func(*args, **kwargs))+ except Exception as e:+ exception_container.append(e)- # Start the function in a new thread- thread = threading.Thread(target=target)+ # Start the function in a new daemon thread+ thread = threading.Thread(target=target, daemon=True)thread.start()thread.join(effective_timeout)@@ -1046,7 +1051,16 @@ def with_timeout(timeout=None):f"exceeded {effective_timeout} seconds.")else:- return result_container[0]+ # If an exception occurred, re-raise it+ if exception_container:+ raise exception_container[0]+ # Return result if available+ if result_container:+ return result_container[0]+ raise RuntimeError(+ f"Function `{func.__name__}` completed but produced "+ "no result or exception."+ )return wrapperdiff --git a/test/utils/test_commons.py b/test/utils/test_commons.pyindex ebed8a80d..498ceeb96 100644--- a/test/utils/test_commons.py+++ b/test/utils/test_commons.py@@ -383,3 +383,59 @@ def test_direct_timeout_no_delay():result = fast_function()assert result == "success"+++def test_timeout_with_exception():+ @with_timeout(2)+ def function_that_raises():+ raise ValueError("Test exception")++ with pytest.raises(ValueError) as exc_info:+ function_that_raises()++ assert "Test exception" in str(exc_info.value)+++def test_timeout_with_exception_type_preserved():+ r"""Test that exception type is preserved when re-raised."""++ class CustomException(Exception):+ pass++ @with_timeout(2)+ def function_with_custom_exception():+ raise CustomException("Custom error message")++ with pytest.raises(CustomException) as exc_info:+ function_with_custom_exception()++ assert "Custom error message" in str(exc_info.value)+++def test_timeout_preserves_traceback():+ r"""Test that the original traceback is preserved when exception is+ re-raised.+ """++ @with_timeout(2)+ def function_with_nested_calls():+ def inner_function():+ def deepest_function():+ raise ValueError("Error from deepest function")++ return deepest_function()++ return inner_function()++ with pytest.raises(ValueError) as exc_info:+ function_with_nested_calls()++ # Check that the traceback contains the function names from the original+ # call stack+ import traceback++ tb_str = ''.join(traceback.format_tb(exc_info.tb))+ # The traceback should contain references to our nested functions+ assert "deepest_function" in tb_str+ assert "inner_function" in tb_str+ assert "Error from deepest function" in str(exc_info.value)diff --git a/test/workforce/test_workflow_memory.py b/test/workforce/test_workflow_memory.pyindex d2e59b7c6..052f7354a 100644--- a/test/workforce/test_workflow_memory.py+++ b/test/workforce/test_workflow_memory.py@@ -26,6 +26,19 @@ from camel.societies.workforce.single_agent_worker import SingleAgentWorkerfrom camel.tasks.task import Task, TaskState[email protected](autouse=True)+def mock_model_backend():+ """Use StubModel to prevent real LLM API calls in tests."""+ from camel.models.stub_model import StubModel+ from camel.types import ModelType++ # Use the existing StubModel designed for unit tests+ stub_model = StubModel(model_type=ModelType.STUB)++ with patch('camel.models.ModelFactory.create', return_value=stub_model):+ yield stub_model++class MockSingleAgentWorker(SingleAgentWorker):"""A mock worker for testing workflow functionality."""