Skip to content

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

Enhance JSON extraction in model output by supporting BaseMessage type and improving HTML tag removal

Magnus Müller3018f5965449
diff --git a/browser_use/agent/message_manager/utils.py b/browser_use/agent/message_manager/utils.py
index b682cbd7e..2413ba62b 100644
--- a/browser_use/agent/message_manager/utils.py
+++ b/browser_use/agent/message_manager/utils.py
@@ -27,9 +27,12 @@ def is_model_without_tool_support(model_name: str) -> bool:
return any(re.match(pattern, model_name) for pattern in MODELS_WITHOUT_TOOL_SUPPORT_PATTERNS)
-def extract_json_from_model_output(content: str) -> dict:
+def extract_json_from_model_output(content: str | BaseMessage) -> dict:
"""Extract JSON from model output, handling both plain JSON and code-block-wrapped JSON."""
try:
+ if isinstance(content, BaseMessage):
+ # for langchain_core.messages.BaseMessage
+ content = content.content
# If content is wrapped in code blocks, extract just the JSON part
if '```' in content:
# Find the JSON content between code blocks
@@ -37,6 +40,18 @@ def extract_json_from_model_output(content: str) -> dict:
# Remove language identifier if present (e.g., 'json\n')
if '\n' in content:
content = content.split('\n', 1)[1]
+
+ # remove html-like tags before the first { and after the last }
+ # This handles cases like <|header_start|>assistant<|header_end|> and <function=AgentOutput>
+ # Only remove content before { if content doesn't already start with {
+ if not content.strip().startswith('{'):
+ content = re.sub(r'^.*?(?=\{)', '', content, flags=re.DOTALL)
+
+ # Remove common HTML-like tags and patterns at the end, but be more conservative
+ # Look for patterns like </function>, <|header_start|>, etc. after the JSON
+ content = re.sub(r'\}(\s*<[^>]*>.*?$)', '}', content, flags=re.DOTALL)
+ content = re.sub(r'\}(\s*<\|[^|]*\|>.*?$)', '}', content, flags=re.DOTALL)
+
# Parse the cleaned content
result_dict = json.loads(content)