Skip to content

Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.

Limit Anthropic tool recovery to thinking

MagMueller4ed239386c82
diff --git a/browser_use/llm/anthropic/chat.py b/browser_use/llm/anthropic/chat.py
index c41aea87b..86ad8ca03 100644
--- a/browser_use/llm/anthropic/chat.py
+++ b/browser_use/llm/anthropic/chat.py
@@ -316,34 +316,36 @@ class ChatAnthropic(BaseChatModel):
if not isinstance(tool_input, dict):
return None
- for value in tool_input.values():
- if not isinstance(value, str):
- continue
+ # The malformed Anthropic response puts the complete call in the schema's
+ # `thinking` argument. Do not promote serialized data from arbitrary fields.
+ thinking = tool_input.get('thinking')
+ if not isinstance(thinking, str):
+ return None
- candidates: list[Any] = []
- tool_call = self._tool_call_from_text(value)
- if tool_call is not None:
- candidates.append(tool_call)
- for text_candidate in self._json_candidates_from_text(value):
- try:
- candidate = json.loads(text_candidate)
- if isinstance(candidate, dict):
- candidate = self._repair_serialized_fields(candidate)
- candidates.append(candidate)
- except (json.JSONDecodeError, TypeError):
- continue
+ candidates: list[Any] = []
+ tool_call = self._tool_call_from_text(thinking)
+ if tool_call is not None:
+ candidates.append(tool_call)
+ for text_candidate in self._json_candidates_from_text(thinking):
+ try:
+ candidate = json.loads(text_candidate)
+ if isinstance(candidate, dict):
+ candidate = self._repair_serialized_fields(candidate)
+ candidates.append(candidate)
+ except (json.JSONDecodeError, TypeError):
+ continue
- for candidate in candidates:
- try:
- completion = output_format.model_validate(candidate)
- except Exception:
- continue
- return ChatInvokeCompletion(
- completion=completion,
- usage=usage,
- stop_reason=response.stop_reason,
- stop_details=self._get_stop_details(response),
- )
+ for candidate in candidates:
+ try:
+ completion = output_format.model_validate(candidate)
+ except Exception:
+ continue
+ return ChatInvokeCompletion(
+ completion=completion,
+ usage=usage,
+ stop_reason=response.stop_reason,
+ stop_details=self._get_stop_details(response),
+ )
return None
diff --git a/tests/ci/test_anthropic_serialized_tool_input.py b/tests/ci/test_anthropic_serialized_tool_input.py
index 811976177..6b68df1bd 100644
--- a/tests/ci/test_anthropic_serialized_tool_input.py
+++ b/tests/ci/test_anthropic_serialized_tool_input.py
@@ -86,6 +86,34 @@ async def test_valid_tool_input_is_untouched(httpserver):
assert result.completion.action == actions
+async def test_valid_tool_input_wins_over_conflicting_serialized_thinking(httpserver):
+ """A valid real action must take priority over a serialized action in thinking."""
+ real_actions = [{'click_element_by_index': {'index': 5}}]
+ serialized_actions = [{'click_element_by_index': {'index': 99}}]
+ serialized = json.dumps({'thinking': 'Conflicting fallback.', 'action': serialized_actions})
+ httpserver.expect_request('/v1/messages', method='POST').respond_with_json(
+ _tool_use_response({'thinking': serialized, 'action': real_actions})
+ )
+
+ result = await _chat(httpserver).ainvoke([UserMessage(content='next step')], output_format=StepOutput)
+
+ assert result.completion.action == real_actions
+ assert result.completion.thinking == serialized
+
+
+async def test_serialized_tool_call_outside_thinking_is_not_recovered(httpserver):
+ """Only the known malformed `thinking` path may be promoted to structured output."""
+ payload = {'thinking': 'Clicking submit.', 'action': [{'click_element_by_index': {'index': 5}}]}
+ httpserver.expect_request('/v1/messages', method='POST').respond_with_json(
+ _tool_use_response({'thinking': 'No structured action was produced.', 'other': json.dumps(payload)})
+ )
+
+ with pytest.raises(ModelProviderError) as exc_info:
+ await _chat(httpserver).ainvoke([UserMessage(content='next step')], output_format=StepOutput)
+
+ assert 'action' in str(exc_info.value)
+
+
async def test_unrecoverable_tool_input_still_raises(httpserver):
"""Recovery must not mask genuinely malformed output."""
httpserver.expect_request('/v1/messages', method='POST').respond_with_json(