🐫 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(agents): catch Anthropic RateLimitError in ChatAgent retry loop (#4140)
Rajan Chavada8c791b7b9cf7
diff --git a/camel/agents/chat_agent.py b/camel/agents/chat_agent.pyindex 6e57acc02..ca172d4d8 100644--- a/camel/agents/chat_agent.py+++ b/camel/agents/chat_agent.py@@ -57,6 +57,11 @@ from openai import ()from pydantic import BaseModel, ValidationError+try:+ from anthropic import RateLimitError as AnthropicRateLimitError+except ImportError:+ AnthropicRateLimitError = None # type: ignore[assignment,misc]+from camel.agents._types import ModelResponse, ToolCallRequestfrom camel.agents._utils import (build_default_summary_prompt,@@ -152,6 +157,11 @@ elif os.environ.get("TRACEROOT_ENABLED", "False").lower() == "true":else:from camel.utils import observe+# Collect rate-limit error types from whichever provider SDKs are installed.+# RateLimitError from openai is always present; anthropic's is optional.+_RATE_LIMIT_ERRORS: tuple = tuple(+ e for e in [RateLimitError, AnthropicRateLimitError] if e is not None+)SIMPLE_FORMAT_PROMPT = TextPrompt(textwrap.dedent(@@ -3660,7 +3670,7 @@ class ChatAgent(BaseAgent):)if response:break- except RateLimitError as e:+ except _RATE_LIMIT_ERRORS as e: # type: ignore[misc]last_error = eif attempt < self.retry_attempts - 1:delay = min(self.retry_delay * (2**attempt), 60.0)@@ -3722,7 +3732,7 @@ class ChatAgent(BaseAgent):)if response:break- except RateLimitError as e:+ except _RATE_LIMIT_ERRORS as e: # type: ignore[misc]last_error = eif attempt < self.retry_attempts - 1:delay = min(self.retry_delay * (2**attempt), 60.0)diff --git a/test/agents/test_chat_agent.py b/test/agents/test_chat_agent.pyindex b3ad66a3e..da43a4161 100644--- a/test/agents/test_chat_agent.py+++ b/test/agents/test_chat_agent.py@@ -2329,3 +2329,45 @@ async def test_chat_agent_async_stream_with_structured_output():assert len(responses) > 1, "Should receive multiple streaming chunks"assert responses[-1].msg.parsed.answer == 6assert responses[-1].msg.parsed.explanation+++def test_rate_limit_retry_on_openai_rate_limit_error():+ r"""RateLimitError from openai triggers retries before raising."""+ from openai import RateLimitError as OpenAIRateLimitError++ from camel.agents.chat_agent import _RATE_LIMIT_ERRORS+ from camel.models import ModelProcessingError++ assert OpenAIRateLimitError in _RATE_LIMIT_ERRORS++ agent = ChatAgent(model=DummyModel(ModelType.GPT_4O_MINI))+ agent.retry_attempts = 3+ agent.retry_delay = 0.0++ error = OpenAIRateLimitError(+ message="rate limit",+ response=MagicMock(status_code=429, headers={}),+ body={},+ )+ agent.model_backend.run = MagicMock(side_effect=error)++ with pytest.raises(ModelProcessingError):+ agent._get_model_response(openai_messages=[], current_iteration=0)++ assert agent.model_backend.run.call_count == agent.retry_attempts+++def test_rate_limit_retry_respects_anthropic_error_when_installed():+ r"""AnthropicRateLimitError, if the package is present, is in the tuple."""+ from camel.agents.chat_agent import (+ _RATE_LIMIT_ERRORS,+ AnthropicRateLimitError,+ )++ if AnthropicRateLimitError is not None:+ assert AnthropicRateLimitError in _RATE_LIMIT_ERRORS+ else:+ # anthropic not installed in this environment — tuple has only openai+ from openai import RateLimitError as OpenAIRateLimitError++ assert _RATE_LIMIT_ERRORS == (OpenAIRateLimitError,)