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
port over merts new llm_error_msg tags
Nick Sweeting8b134dd25a9f
diff --git a/browser_use/browser/default_action_watchdog.py b/browser_use/browser/default_action_watchdog.pyindex 66c941042..fc0c2f7ba 100644--- a/browser_use/browser/default_action_watchdog.py+++ b/browser_use/browser/default_action_watchdog.py@@ -231,16 +231,29 @@ class DefaultActionWatchdog(BaseWatchdog):if tag_name == 'select':try:- dropdown_options = await self.event_bus.dispatch(GetDropdownOptionsEvent(node=element_node)).event_result(raise_if_none=True) or {}+ dropdown_options = (+ await self.event_bus.dispatch(GetDropdownOptionsEvent(node=element_node)).event_result(raise_if_none=True)+ or {}+ )except Exception as e:self.logger.warning(f'Failed to get dropdown options: {type(e).__name__}: {e}')dropdown_options = {}- available_options = ("Available options: [" + ", ".join(dropdown_options.keys()) + "]") if dropdown_options else "Call get_dropdown_options() to get available options list."- self.logger.warning(f'Cannot click on <select> elements. Use select_dropdown_option() action instead. {available_options}]')- raise Exception(f'Cannot click on <select> elements. Use select_dropdown_option() action instead. {available_options}')+ available_options = (+ ('Available options: [' + ', '.join(dropdown_options.keys()) + ']')+ if dropdown_options+ else 'Call get_dropdown_options() to get available options list.'+ )+ self.logger.warning(+ f'Cannot click on <select> elements. Use select_dropdown_option() action instead. {available_options}]'+ )+ raise Exception(+ f'<llm_error_msg>Cannot click on <select> elements. Use select_dropdown_option() action instead. {available_options}</llm_error_msg>'+ )if tag_name == 'input' and element_type == 'file':- raise Exception('Cannot click on file input elements. File uploads must be handled using upload_file_to_element()')+ raise Exception(+ '<llm_error_msg>Cannot click on file input elements. File uploads must be handled using upload_file_to_element()</llm_error_msg>'+ )# Get CDP clientcdp_session = await self.browser_session.get_or_create_cdp_session(target_id=element_node.target_id, focus=False)@@ -529,11 +542,13 @@ class DefaultActionWatchdog(BaseWatchdog):raise eexcept Exception as e:# Extract key element info for error message- element_info = f"<{element_node.tag_name or 'unknown'}"+ element_info = f'<{element_node.tag_name or "unknown"}'if element_node.element_index:- element_info += f" index={element_node.element_index}"- element_info += ">"- raise Exception(f'<llm_error_msg>Failed to click element {element_info}. The element may not be interactable or visible.</llm_error_msg> Details: {str(e)}')+ element_info += f' index={element_node.element_index}'+ element_info += '>'+ raise Exception(+ f'<llm_error_msg>Failed to click element {element_info}. The element may not be interactable or visible.</llm_error_msg> Details: {type(e).__name__}: {e}'+ )async def _type_to_page(self, text: str):"""@@ -1185,7 +1200,9 @@ class DefaultActionWatchdog(BaseWatchdog):# Check if it's a file inputif not self.browser_session.is_file_input(element_node):- raise Exception(f'<llm_error_msg>Element {index_for_logging} is not a file input. Use click_element_by_index for non-file input elements.</llm_error_msg>')+ raise Exception(+ f'<llm_error_msg>Element {index_for_logging} is not a file input. Use click_element_by_index for non-file input elements.</llm_error_msg>'+ )# Get CDP client and sessioncdp_client = self.browser_session.cdp_client@@ -1492,7 +1509,7 @@ class DefaultActionWatchdog(BaseWatchdog):'element_info': element_info,'source': source_info,'formatted_options': '\n'.join(formatted_options),- 'message': msg+ 'message': msg,}except Exception as e:@@ -1738,13 +1755,13 @@ class DefaultActionWatchdog(BaseWatchdog):if selection_result.get('success'):msg = selection_result.get('message', f'Selected option: {target_text}')self.logger.info(f'✅ {msg}')-+# Return the result as a dictreturn {'success': 'true','message': msg,'value': selection_result.get('value', target_text),- 'element_index': str(index_for_logging)+ 'element_index': str(index_for_logging),}else:error_msg = selection_result.get('error', f'Failed to select option: {target_text}')diff --git a/browser_use/controller/service.py b/browser_use/controller/service.pyindex 7e9785918..b3f1f6b5d 100644--- a/browser_use/controller/service.py+++ b/browser_use/controller/service.py@@ -67,21 +67,21 @@ T = TypeVar('T', bound=BaseModel)def extract_llm_error_message(error: Exception) -> str:"""Extract the clean error message from an exception that may contain <llm_error_msg> tags.-+If the tags are found, returns the content between them.Otherwise, returns the original error string."""import re-+error_str = str(error)-+# Look for content between <llm_error_msg> tagspattern = r'<llm_error_msg>(.*?)</llm_error_msg>'match = re.search(pattern, error_str, re.DOTALL)-+if match:return match.group(1).strip()-+# Fallback: return the original error stringreturn error_str@@ -176,9 +176,7 @@ class Controller(Generic[Context]):memory = f"Searched Google for '{params.query}'"msg = f'🔍 {memory}'logger.info(msg)- return ActionResult(- extracted_content=memory, include_in_memory=True, long_term_memory=memory- )+ return ActionResult(extracted_content=memory, include_in_memory=True, long_term_memory=memory)except Exception as e:logger.error(f'Failed to search Google: {e}')clean_msg = extract_llm_error_message(e)@@ -471,9 +469,7 @@ class Controller(Generic[Context]):memory = f'Switched to tab #{params.page_id}'msg = f'🔄 {memory}'logger.info(msg)- return ActionResult(- extracted_content=memory, include_in_memory=True, long_term_memory=memory- )+ return ActionResult(extracted_content=memory, include_in_memory=True, long_term_memory=memory)except Exception as e:logger.error(f'Failed to switch tab: {e}')clean_msg = extract_llm_error_message(e)@@ -595,7 +591,9 @@ Provide the extracted information in a clear, structured format."""else:save_result = await file_system.save_extracted_content(extracted_content)current_url = await browser_session.get_current_page_url()- memory = f'Extracted content from {current_url} for query: {query}\nContent saved to file system: {save_result}'+ memory = (+ f'Extracted content from {current_url} for query: {query}\nContent saved to file system: {save_result}'+ )include_extracted_content_only_once = Truelogger.info(f'📄 {memory}')@@ -716,9 +714,10 @@ Provide the extracted information in a clear, structured format."""raise ValueError(f'Element index {params.index} not found in DOM')# Dispatch GetDropdownOptionsEvent to the event handler- from browser_use.browser.events import GetDropdownOptionsEventimport json-++ from browser_use.browser.events import GetDropdownOptionsEvent+event = browser_session.event_bus.dispatch(GetDropdownOptionsEvent(node=node))dropdown_data = await event.event_result()@@ -728,7 +727,7 @@ Provide the extracted information in a clear, structured format."""# Extract the message from the returned datamsg = dropdown_data.get('message', '')options_count = len(json.loads(dropdown_data.get('options', '[]'))) # Parse the string back to list to get count-+return ActionResult(extracted_content=msg,include_in_memory=True,@@ -749,7 +748,7 @@ Provide the extracted information in a clear, structured format."""# Dispatch SelectDropdownOptionEvent to the event handlerfrom browser_use.browser.events import SelectDropdownOptionEvent-+event = browser_session.event_bus.dispatch(SelectDropdownOptionEvent(node=node, text=params.text))selection_data = await event.event_result()@@ -758,7 +757,7 @@ Provide the extracted information in a clear, structured format."""# Extract the message from the returned datamsg = selection_data.get('message', f'Selected option: {params.text}')-+return ActionResult(extracted_content=msg,include_in_memory=True,