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
fallback parser for groq
Gregor Žuničbf9ea1e33a56
diff --git a/browser_use/llm/groq/chat.py b/browser_use/llm/groq/chat.pyindex 57028d79f..99d73b77c 100644--- a/browser_use/llm/groq/chat.py+++ b/browser_use/llm/groq/chat.py@@ -1,3 +1,4 @@+import loggingfrom dataclasses import dataclassfrom typing import Literal, TypeVar, overload@@ -21,6 +22,7 @@ from pydantic import BaseModelfrom browser_use.llm.base import BaseChatModel, ChatInvokeCompletionfrom browser_use.llm.exceptions import ModelProviderError, ModelRateLimitError+from browser_use.llm.groq.parser import try_parse_groq_failed_generationfrom browser_use.llm.groq.serializer import GroqMessageSerializerfrom browser_use.llm.messages import BaseMessagefrom browser_use.llm.views import ChatInvokeUsage@@ -31,6 +33,8 @@ GroqVerifiedModels = Literal[T = TypeVar('T', bound=BaseModel)+logger = logging.getLogger(__name__)+@dataclassclass ChatGroq(BaseChatModel):@@ -111,7 +115,6 @@ class ChatGroq(BaseChatModel):name=output_format.__name__,description='Model output schema',schema=schema,- strict=True,),type='json_schema',),@@ -135,8 +138,28 @@ class ChatGroq(BaseChatModel):except RateLimitError as e:raise ModelRateLimitError(message=e.response.text, status_code=e.response.status_code, model=self.name) from e- except (APIResponseValidationError, APIStatusError) as e:+ except APIResponseValidationError as e:raise ModelProviderError(message=e.response.text, status_code=e.response.status_code, model=self.name) from e++ except APIStatusError as e:+ if output_format is None:+ raise ModelProviderError(message=e.response.text, status_code=e.response.status_code, model=self.name) from e+ else:+ try:+ logger.debug(f'Groq failed generation: {e.response.text}; fallback to manual parsing')++ parsed_response = try_parse_groq_failed_generation(e, output_format)++ logger.debug('Manual error parsing successful ✅')++ return ChatInvokeCompletion(+ completion=parsed_response,+ usage=None, # because this is a hacky way to get the outputs+ # TODO: @groq needs to fix their parsers and validators+ )+ except Exception as _:+ raise ModelProviderError(message=str(e), status_code=e.response.status_code, model=self.name) from e+except APIError as e:raise ModelProviderError(message=e.message, model=self.name) from eexcept Exception as e:diff --git a/browser_use/llm/groq/parser.py b/browser_use/llm/groq/parser.pynew file mode 100644index 000000000..541381c54--- /dev/null+++ b/browser_use/llm/groq/parser.py@@ -0,0 +1,159 @@+import json+import logging+import re+from typing import TypeVar++from groq import APIStatusError+from pydantic import BaseModel++logger = logging.getLogger(__name__)++T = TypeVar('T', bound=BaseModel)+++class ParseFailedGenerationError(Exception):+ pass+++def try_parse_groq_failed_generation(+ error: APIStatusError,+ output_format: type[T],+) -> T:+ """Extract JSON from model output, handling both plain JSON and code-block-wrapped JSON."""+ try:+ content = error.body['error']['failed_generation'] # type: ignore++ # If content is wrapped in code blocks, extract just the JSON part+ if '```' in content:+ # Find the JSON content between code blocks+ content = content.split('```')[1]+ # 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)++ # Handle extra characters after the JSON, including stray braces+ # Find the position of the last } that would close the main JSON object+ content = content.strip()++ if content.endswith('}'):+ # Try to parse and see if we get valid JSON+ try:+ json.loads(content)+ except json.JSONDecodeError:+ # If parsing fails, try to find the correct end of the JSON+ # by counting braces and removing anything after the balanced JSON+ brace_count = 0+ last_valid_pos = -1+ for i, char in enumerate(content):+ if char == '{':+ brace_count += 1+ elif char == '}':+ brace_count -= 1+ if brace_count == 0:+ last_valid_pos = i + 1+ break++ if last_valid_pos > 0:+ content = content[:last_valid_pos]++ # Fix control characters in JSON strings before parsing+ # This handles cases where literal control characters appear in JSON values+ content = _fix_control_characters_in_json(content)++ # Parse the cleaned content+ result_dict = json.loads(content)++ # some models occasionally respond with a list containing one dict: https://github.com/browser-use/browser-use/issues/1458+ if isinstance(result_dict, list) and len(result_dict) == 1 and isinstance(result_dict[0], dict):+ result_dict = result_dict[0]++ assert isinstance(result_dict, dict), f'Expected JSON dictionary in response, got JSON {type(result_dict)} instead'+ logger.debug(f'Successfully parsed model output: {result_dict}')+ return output_format.model_validate(result_dict)++ except KeyError as e:+ raise ParseFailedGenerationError(e) from e++ except json.JSONDecodeError as e:+ logger.warning(f'Failed to parse model output: {content} {str(e)}')+ raise ValueError(f'Could not parse response. {str(e)}')++ except Exception as e:+ raise ParseFailedGenerationError(error.response.text) from e+++def _fix_control_characters_in_json(content: str) -> str:+ """Fix control characters in JSON string values to make them valid JSON."""+ try:+ # First try to parse as-is to see if it's already valid+ json.loads(content)+ return content+ except json.JSONDecodeError:+ pass++ # More sophisticated approach: only escape control characters inside string values+ # while preserving JSON structure formatting++ result = []+ i = 0+ in_string = False+ escaped = False++ while i < len(content):+ char = content[i]++ if not in_string:+ # Outside of string - check if we're entering a string+ if char == '"':+ in_string = True+ result.append(char)+ else:+ # Inside string - handle escaping and control characters+ if escaped:+ # Previous character was backslash, so this character is escaped+ result.append(char)+ escaped = False+ elif char == '\\':+ # This is an escape character+ result.append(char)+ escaped = True+ elif char == '"':+ # End of string+ result.append(char)+ in_string = False+ elif char == '\n':+ # Literal newline inside string - escape it+ result.append('\\n')+ elif char == '\r':+ # Literal carriage return inside string - escape it+ result.append('\\r')+ elif char == '\t':+ # Literal tab inside string - escape it+ result.append('\\t')+ elif char == '\b':+ # Literal backspace inside string - escape it+ result.append('\\b')+ elif char == '\f':+ # Literal form feed inside string - escape it+ result.append('\\f')+ elif ord(char) < 32:+ # Other control characters inside string - convert to unicode escape+ result.append(f'\\u{ord(char):04x}')+ else:+ # Normal character inside string+ result.append(char)++ i += 1++ return ''.join(result)diff --git a/browser_use/llm/tests/test_groq_loop.py b/browser_use/llm/tests/test_groq_loop.pyindex 5c3c06af4..4b70a75b0 100644--- a/browser_use/llm/tests/test_groq_loop.py+++ b/browser_use/llm/tests/test_groq_loop.py@@ -14,6 +14,10 @@ llm = ChatGroq(async def main():from pydantic import BaseModel+ from browser_use.tokens.service import TokenCost++ tk = TokenCost().register_llm(llm)+class Output(BaseModel):reasoning: stranswer: str@@ -23,17 +27,17 @@ async def main():UserMessage(content=[ContentText(- text=r"Why is the sky blue? write exactly this into reasoning make sure to output ' with \ exactly like in the input : "+ text=r"Why is the sky blue? write exactly this into reasoning make sure to output ' with exactly like in the input : "),ContentText(text="""- The user\'s request is to find the lowest priced women\'s plus size one piece swimsuit in color black with a customer rating of at least 5 on Kohls.com. I am currently on the homepage of Kohls. The page has a search bar and various category links. To begin, I need to navigate to the women\'s section and search for swimsuits. I will start by clicking on the \\'Women\\' category link."""+ The user's request is to find the lowest priced women's plus size one piece swimsuit in color black with a customer rating of at least 5 on Kohls.com. I am currently on the homepage of Kohls. The page has a search bar and various category links. To begin, I need to navigate to the women's section and search for swimsuits. I will start by clicking on the 'Women' category link."""),]),]- for i in range(5):+ for i in range(10):print('-' * 50)print(f'start loop {i}')response = await llm.ainvoke(message, output_format=Output)diff --git a/examples/models/llama4-groq.py b/examples/models/llama4-groq.pyindex 6546bdd5a..ac6c9bf7e 100644--- a/examples/models/llama4-groq.py+++ b/examples/models/llama4-groq.py@@ -5,17 +5,21 @@ import syssys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))from dotenv import load_dotenv+from lmnr import Laminarload_dotenv()+Laminar.initialize()++from browser_use import Agentfrom browser_use.llm import ChatGroqgroq_api_key = os.environ.get('GROQ_API_KEY')llm = ChatGroq(model='meta-llama/llama-4-maverick-17b-128e-instruct',- temperature=0.0,+ # temperature=0.1,)# llm = ChatGroq(@@ -24,7 +28,7 @@ llm = ChatGroq(# temperature=0.0,# )-task = 'Find the founders of browser-use'+task = 'Go to amazon.com, search for laptop, sort by best rating, and give me the price of the first result'async def main():