Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.
Python ai-agentsai-toolsbrowser-agentbrowser-automationbrowser-usecdpcloud-browsercomputer-useheadless-browserllmmcpplaywrightpythonremote-browserstealth-browserweb-automationweb-scraping
fix: handle unexpected response types in ChatAnthropic
claude[bot]cedb0d9cd408
diff --git a/browser_use/llm/anthropic/chat.py b/browser_use/llm/anthropic/chat.pyindex 8f0ea36aa..861fd5b0b 100644--- a/browser_use/llm/anthropic/chat.py+++ b/browser_use/llm/anthropic/chat.py@@ -145,6 +145,14 @@ class ChatAnthropic(BaseChatModel):**self._get_client_params_for_invoke(),)+ # Ensure we have a valid Message object before accessing attributes+ if not isinstance(response, Message):+ raise ModelProviderError(+ message=f'Unexpected response type from Anthropic API: {type(response).__name__}. Response: {str(response)[:200]}',+ status_code=502,+ model=self.name,+ )+usage = self._get_usage(response)# Extract text from the first content block@@ -189,6 +197,14 @@ class ChatAnthropic(BaseChatModel):**self._get_client_params_for_invoke(),)+ # Ensure we have a valid Message object before accessing attributes+ if not isinstance(response, Message):+ raise ModelProviderError(+ message=f'Unexpected response type from Anthropic API: {type(response).__name__}. Response: {str(response)[:200]}',+ status_code=502,+ model=self.name,+ )+usage = self._get_usage(response)# Extract the tool use blockdiff --git a/tests/ci/test_anthropic_502_error.py b/tests/ci/test_anthropic_502_error.pynew file mode 100644index 000000000..3d6027dc1--- /dev/null+++ b/tests/ci/test_anthropic_502_error.py@@ -0,0 +1,86 @@+"""Test for handling Anthropic 502 errors"""++import pytest+from anthropic import APIStatusError+from httpx import Response+from browser_use.llm.anthropic.chat import ChatAnthropic+from browser_use.llm.messages import UserMessage+from browser_use.llm.exceptions import ModelProviderError+++async def test_anthropic_502_error_handling():+ """Test that ChatAnthropic properly handles 502 errors from the API"""+ # Create a ChatAnthropic instance+ chat = ChatAnthropic(+ model="claude-3-5-sonnet-20240620",+ api_key="test-key"+ )++ # Create test messages+ messages = [UserMessage(content="Test message")]++ # Mock the client to raise a 502 error+ class MockClient:+ class Messages:+ async def create(self, **kwargs):+ # Simulate a 502 error from Anthropic API+ import httpx+ request = httpx.Request("POST", "https://api.anthropic.com/v1/messages")+ response = httpx.Response(+ status_code=502,+ headers={},+ content=b"Bad Gateway",+ request=request+ )+ raise APIStatusError(+ message="Bad Gateway",+ response=response,+ body={"error": {"message": "Bad Gateway", "type": "server_error"}}+ )++ messages = Messages()++ # Replace the client with our mock+ chat.get_client = lambda: MockClient()++ # Test that the error is properly caught and re-raised as ModelProviderError+ with pytest.raises(ModelProviderError) as exc_info:+ await chat.ainvoke(messages)++ # Verify the error details+ assert exc_info.value.args[0] == "Bad Gateway"+ assert exc_info.value.args[1] == 502+ assert str(exc_info.value) == "('Bad Gateway', 502)"+++async def test_anthropic_error_does_not_access_usage():+ """Test that error handling doesn't try to access usage attribute on error responses"""+ chat = ChatAnthropic(+ model="claude-3-5-sonnet-20240620",+ api_key="test-key"+ )++ messages = [UserMessage(content="Test message")]++ # Mock the client to return a string instead of a proper response+ class MockClient:+ class Messages:+ async def create(self, **kwargs):+ # This simulates what might happen if the API returns an unexpected response+ # that gets parsed as a string+ return "Error: Bad Gateway"++ messages = Messages()++ chat.get_client = lambda: MockClient()++ # This should raise a ModelProviderError with a clear message+ with pytest.raises(ModelProviderError) as exc_info:+ await chat.ainvoke(messages)++ # The error should be about unexpected response type, not missing 'usage' attribute+ assert "'str' object has no attribute 'usage'" not in str(exc_info.value)+ assert "Unexpected response type from Anthropic API" in str(exc_info.value)+ assert exc_info.value.args[1] == 502\ No newline at end of file