Skip to content

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

Merge branch 'main' into mert/new_everything

mertunsall0c34c399dbf8
diff --cc .github/workflows/eval.yaml
index d9f3a8ace,d581a127e..044f6b4e6
--- a/.github/workflows/eval.yaml
+++ b/.github/workflows/eval.yaml
@@@ -7,8 -8,10 +8,10 @@@ on
jobs:
run_evaluation:
runs-on: ubuntu-latest
- timeout-minutes: 60
+ timeout-minutes: 360
env:
+ #IN_DOCKER: 'true'
+ #ANONYMIZED_TELEMETRY: 'false'
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
diff --cc browser_use/agent/service.py
index ebadf50c7,a1512189e..bf898fc88
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@@ -17,9 -15,8 +17,7 @@@ from typing import Any, Generic, TypeVa
from dotenv import load_dotenv
- from browser_use.browser.session import DEFAULT_BROWSER_PROFILE
-
load_dotenv()
-
from langchain_core.language_models.chat_models import BaseChatModel
from langchain_core.messages import (
BaseMessage,
@@@ -69,7 -66,7 +68,13 @@@ from browser_use.telemetry.service impo
from browser_use.telemetry.views import (
AgentTelemetryEvent,
)
- from browser_use.utils import get_browser_use_version, handle_llm_error, time_execution_async, time_execution_sync
-from browser_use.utils import _log_pretty_path, get_browser_use_version, time_execution_async, time_execution_sync
++from browser_use.utils import (
++ _log_pretty_path,
++ get_browser_use_version,
++ handle_llm_error,
++ time_execution_async,
++ time_execution_sync,
++)
logger = logging.getLogger(__name__)
@@@ -83,17 -80,16 +88,17 @@@ def log_response(response: AgentOutput
if logger is None:
logger = logging.getLogger(__name__)
- if 'Success' in response.current_state.evaluation_previous_goal:
+ if 'success' in response.current_state.evaluation_previous_goal.lower():
emoji = 'πŸ‘'
- elif 'Failed' in response.current_state.evaluation_previous_goal:
+ elif 'failure' in response.current_state.evaluation_previous_goal.lower():
emoji = '⚠️'
else:
- emoji = '❓'
+ emoji = '❔'
+ logger.info(f'πŸ’‘ Thinking:\n{response.current_state.thinking}')
logger.info(f'{emoji} Eval: {response.current_state.evaluation_previous_goal}')
logger.info(f'🧠 Memory: {response.current_state.memory}')
- logger.info(f'🎯 Next goal: {response.current_state.next_goal}')
+ logger.info(f'🎯 Next goal: {response.current_state.next_goal}\n')
Context = TypeVar('Context')
@@@ -170,7 -169,7 +178,8 @@@ class Agent(Generic[Context])
enable_memory: bool = True,
memory_config: MemoryConfig | None = None,
source: str | None = None,
+ file_system_path: str | None = None,
+ task_id: str | None = None,
):
if page_extraction_llm is None:
page_extraction_llm = llm
diff --cc browser_use/controller/service.py
index c83779133,fe067a8ba..1f9351128
--- a/browser_use/controller/service.py
+++ b/browser_use/controller/service.py
@@@ -166,7 -174,7 +202,7 @@@ class Controller(Generic[Context])
if await browser_session.find_file_upload_element_by_index(params.index) is not None:
msg = f'Index {params.index} - has an element which opens file upload dialog. To upload files please use a specific function to upload files '
logger.info(msg)
- return ActionResult(extracted_content=msg, include_in_memory=True, memory=f'Clicked element {params.index}')
- return ActionResult(extracted_content=msg, include_in_memory=True, success=False)
++ return ActionResult(extracted_content=msg, include_in_memory=True, success=False, memory=msg)
msg = None
@@@ -184,10 -192,19 +220,21 @@@
msg += f' - {new_tab_msg}'
logger.info(new_tab_msg)
await browser_session.switch_to_tab(-1)
- return ActionResult(extracted_content=msg, include_in_memory=True, memory=f'Clicked element {params.index}')
- return ActionResult(extracted_content=msg, include_in_memory=True, success=True)
++ return ActionResult(
++ extracted_content=msg, include_in_memory=True, success=True, memory=f'Clicked element {params.index}'
++ )
except Exception as e:
- logger.warning(f'Element not clickable with index {params.index} - most likely the page changed')
- return ActionResult(error=str(e))
+ error_msg = str(e)
+ if 'Execution context was destroyed' in error_msg or 'Cannot find context with specified id' in error_msg:
+ # Page navigated during click - refresh state and return it
+ logger.info('Page context changed during click, refreshing state...')
+ await browser_session.get_state_summary(cache_clickable_elements_hashes=True)
+ return ActionResult(
+ error='Page navigated during click. Refreshed state provided.', include_in_memory=True, success=False
+ )
+ else:
+ logger.warning(f'Element not clickable with index {params.index} - most likely the page changed')
+ return ActionResult(error=error_msg, success=False)
@self.registry.action(
'Input text into a input interactive element',
@@@ -226,19 -241,23 +273,23 @@@
@self.registry.action('Switch tab', param_model=SwitchTabAction)
async def switch_tab(params: SwitchTabAction, browser_session: BrowserSession):
await browser_session.switch_to_tab(params.page_id)
- # Wait for tab to be ready and ensure references are synchronized
page = await browser_session.get_current_page()
- await page.wait_for_load_state()
- msg = f'πŸ”„ Switched to tab {params.page_id}'
+ try:
+ await page.wait_for_load_state(state='domcontentloaded', timeout=5_000)
+ # page was already loaded when we first navigated, this is additional to wait for onfocus/onblur animations/ajax to settle
+ except Exception as e:
+ pass
+ msg = f'πŸ”„ Switched to tab #{params.page_id} with url {page.url}'
logger.info(msg)
- return ActionResult(extracted_content=msg, include_in_memory=True)
+ return ActionResult(extracted_content=msg, include_in_memory=True, memory=f'Switched to tab {params.page_id}')
@self.registry.action('Open a specific url in new tab', param_model=OpenTabAction)
async def open_tab(params: OpenTabAction, browser_session: BrowserSession):
- await browser_session.create_new_tab(params.url)
- msg = f'πŸ”— Opened new tab with {params.url}'
+ page = await browser_session.create_new_tab(params.url)
+ tab_idx = browser_session.tabs.index(page)
+ msg = f'πŸ”— Opened new tab #{tab_idx} with url {params.url}'
logger.info(msg)
- return ActionResult(extracted_content=msg, include_in_memory=True)
+ return ActionResult(extracted_content=msg, include_in_memory=True, memory=f'Opened new tab with URL {params.url}')
@self.registry.action('Close an existing tab', param_model=CloseTabAction)
async def close_tab(params: CloseTabAction, browser_session: BrowserSession):
@@@ -276,26 -297,29 +333,38 @@@
# manually append iframe text into the content so it's readable by the LLM (includes cross-origin iframes)
for iframe in page.frames:
+ try:
+ await iframe.wait_for_load_state(timeout=5000) # extra on top of already loaded page
+ except Exception as e:
+ pass
+
if iframe.url != page.url and not iframe.url.startswith('data:'):
content += f'\n\nIFRAME {iframe.url}:\n'
- content += markdownify.markdownify(await iframe.content())
+ # Run markdownify in a thread pool for iframe content as well
+ try:
+ iframe_html = await iframe.content()
+ iframe_markdown = await loop.run_in_executor(None, markdownify_func, iframe_html)
+ except Exception as e:
+ logger.debug(f'Error extracting iframe content from within page {page.url}: {type(e).__name__}: {e}')
+ iframe_markdown = ''
+ content += iframe_markdown
- prompt = 'Your task is to extract the content of the page. You will be given a page and a goal and you should extract all relevant information around this goal from the page. If the goal is vague, summarize the page. Respond in json format. Extraction goal: {goal}, Page: {page}'
- template = PromptTemplate(input_variables=['goal', 'page'], template=prompt)
+ # limit to 60000 characters - remove text in the middle this is approx 20000 tokens
+ if len(content) > 60000:
+ content = content[:30000] + '... left out the middle because it was too long ...' + content[-30000:]
+
+ prompt = 'You convert websites into structured information. Extract information from this webpage based on the query. Focus only on content relevant to the query. If the query is vague or does not make sense for the page, provide a brief summary of the page. Respond in JSON format.\nQuery: {content_to_extract}\n answer:\n{page}'
+ template = PromptTemplate(input_variables=['content_to_extract', 'page'], template=prompt)
try:
- output = await page_extraction_llm.ainvoke(template.format(goal=goal, page=content))
- msg = f'πŸ“„ Extracted from page\n: {output.content}\n'
- logger.info(msg)
- return ActionResult(extracted_content=msg, include_in_memory=True)
+ output = await page_extraction_llm.ainvoke(template.format(content_to_extract=content_to_extract, page=content))
+ output_text = output.content
+ msg = f'πŸ“„ Extracted from page\n: {output_text}\n'
+ logger.info(msg + f' for query "{content_to_extract}"')
+ return ActionResult(
+ extracted_content=msg,
+ include_in_memory=False,
+ update_read_state=True,
+ )
except Exception as e:
logger.debug(f'Error extracting content: {e}')
msg = f'πŸ“„ Extracted from page\n: {content}\n'