Skip to content

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

more type hint fixes

Nick Sweetingaad78d93abf3
diff --git a/eval/service.py b/eval/service.py
index d7ea9992b..a723e63c5 100644
--- a/eval/service.py
+++ b/eval/service.py
@@ -491,7 +491,7 @@ from langchain_google_genai import ChatGoogleGenerativeAI
from langchain_openai import ChatOpenAI
from pydantic.types import SecretStr
-from browser_use import ActionResult, Agent, BrowserSession, Controller
+from browser_use import ActionResult, Agent, BrowserProfile, BrowserSession, Controller
from browser_use.agent.memory import MemoryConfig
from browser_use.agent.views import AgentHistoryList
@@ -1279,7 +1279,7 @@ async def setup_browser_session(task: Task, headless: bool) -> BrowserSession:
logger.debug(f'Browser setup: Initializing BrowserSession for task {task.task_id}')
# Use incognito mode (user_data_dir=None) for evaluations to avoid state pollution
- browser_session = BrowserSession(
+ profile = BrowserProfile(
user_data_dir=None, # Incognito mode - no persistent state
headless=headless,
chromium_sandbox=False, # running in docker
@@ -1293,6 +1293,8 @@ async def setup_browser_session(task: Task, headless: bool) -> BrowserSession:
# ignore_https_errors=True, # some eval tasks have http:// or broken https sites in them
)
+ browser_session = BrowserSession(browser_profile=profile)
+
# Start browser session
logger.debug(f'Browser setup: Starting browser session for task {task.task_id}')
await browser_session.start()
@@ -1307,7 +1309,7 @@ async def setup_browser_session(task: Task, headless: bool) -> BrowserSession:
return browser_session
-@observe(name='executor', span_type='EXECUTOR')
+@observe(name='executor', span_type='EXECUTOR') # type: ignore[arg-type]
async def run_agent_with_browser(
browser_session: BrowserSession,
task: Task,
@@ -1350,7 +1352,7 @@ async def run_agent_with_browser(
return agent.state.history
-@observe(name='evaluate_task_result', span_type='EVALUATOR')
+@observe(name='evaluate_task_result', span_type='EVALUATOR') # type: ignore[arg-type]
async def evaluate_task_result(eval_model: BaseChatModel, task_folder: Path) -> dict:
"""Evaluate the task result"""
return await judge_task_result(eval_model, task_folder, score_threshold=3)
@@ -1391,7 +1393,7 @@ def determine_current_stage(completed_stages: set) -> Stage:
return Stage.LOAD_EXISTING # Default starting stage
-@observe(name='evaluation', span_type='EVALUATION')
+@observe(name='evaluation', span_type='EVALUATION') # type: ignore[arg-type]
async def run_task_with_semaphore(
task: Task,
run_id: str,
diff --git a/examples/custom-functions/advanced_search.py b/examples/custom-functions/advanced_search.py
index d22d9c95f..cf13cdbfa 100644
--- a/examples/custom-functions/advanced_search.py
+++ b/examples/custom-functions/advanced_search.py
@@ -1,5 +1,5 @@
import asyncio
-import http
+import http.client
import json
import os
import sys
diff --git a/examples/custom-functions/extract_pdf_content.py b/examples/custom-functions/extract_pdf_content.py
index 3b3070748..20ab2de47 100755
--- a/examples/custom-functions/extract_pdf_content.py
+++ b/examples/custom-functions/extract_pdf_content.py
@@ -15,7 +15,6 @@ load_dotenv()
import asyncio
import logging
-from typing import Any
from langchain_openai import ChatOpenAI
from mistralai import Mistral # type: ignore
@@ -44,7 +43,7 @@ class PdfExtractParams(BaseModel):
'Extract PDF Text',
param_model=PdfExtractParams,
)
-def extract_mistral_ocr(params: PdfExtractParams, browser: BrowserContext) -> dict[str, Any]:
+def extract_mistral_ocr(params: PdfExtractParams, browser: BrowserContext) -> ActionResult:
"""
Process a PDF URL using Mistral OCR API and return the OCR response.
diff --git a/examples/features/custom_vector_store.py b/examples/features/custom_vector_store.py
index ec42b3151..b6535ed71 100644
--- a/examples/features/custom_vector_store.py
+++ b/examples/features/custom_vector_store.py
@@ -59,19 +59,22 @@ async def run_agent_with_memory_config(
# Let's refine how to access summaries. The summary is added as a 'memory' type message.
summaries_created = []
- for step_messages in agent.message_manager.state.history.get_messages():
- if isinstance(step_messages, list):
- for msg in step_messages:
- if (
- hasattr(msg, 'additional_kwargs')
- and msg.additional_kwargs.get('metadata', {}).get('message_type') == 'memory'
- ):
- summaries_created.append(msg.content)
- elif (
- hasattr(step_messages, 'additional_kwargs')
- and step_messages.additional_kwargs.get('metadata', {}).get('message_type') == 'memory'
- ): # if it's a list of messages
- summaries_created.append(step_messages.content)
+ for item in agent.message_manager.state.history.get_messages():
+ # get_messages() returns tuples of (step_number, messages)
+ if isinstance(item, tuple) and len(item) == 2:
+ step_number, step_messages = item
+ if isinstance(step_messages, list):
+ for msg in step_messages:
+ if (
+ hasattr(msg, 'additional_kwargs')
+ and msg.additional_kwargs.get('metadata', {}).get('message_type') == 'memory'
+ ):
+ summaries_created.append(msg.content)
+ elif (
+ hasattr(step_messages, 'additional_kwargs')
+ and step_messages.additional_kwargs.get('metadata', {}).get('message_type') == 'memory'
+ ):
+ summaries_created.append(step_messages.content)
if summaries_created:
print('\nProcedural Summaries Created during run:')
@@ -169,5 +172,9 @@ if __name__ == '__main__':
import sys
if sys.platform.startswith('win'):
- asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy())
+ # WindowsProactorEventLoopPolicy is only available on Windows
+ try:
+ asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy())
+ except AttributeError:
+ pass # Not on Windows, ignore
asyncio.run(main())
diff --git a/examples/features/save_trace.py b/examples/features/save_trace.py
index 65e1c0803..b0701fd07 100644
--- a/examples/features/save_trace.py
+++ b/examples/features/save_trace.py
@@ -19,7 +19,7 @@ llm = ChatOpenAI(model='gpt-4o', temperature=0.0)
async def main():
browser_session = BrowserSession(
browser_profile=BrowserProfile(
- trace_path='./tmp/traces/',
+ traces_dir='./tmp/traces/',
user_data_dir='~/.config/browseruse/profiles/default',
)
)
diff --git a/tests/ci/test_browser_session_output_paths.py b/tests/ci/test_browser_session_output_paths.py
index 963883362..3c3670d90 100644
--- a/tests/ci/test_browser_session_output_paths.py
+++ b/tests/ci/test_browser_session_output_paths.py
@@ -194,6 +194,7 @@ class TestAgentRecordings:
for gif in gif_files:
gif.unlink()
else: # custom_path
+ assert expected_gif_path is not None, 'expected_gif_path should be set for custom_path'
assert expected_gif_path.exists(), f'GIF was not created at {expected_gif_path}'
finally:
await browser_session.stop()
@@ -216,11 +217,13 @@ class TestBrowserProfileRecordings:
video_dir = test_dir / f'videos_{context_type}_{alias}'
user_data_dir = None if context_type == 'incognito' else str(test_dir / 'user_data')
- browser_session = BrowserSession(
- browser_profile=BrowserProfile(
- headless=True, disable_security=True, user_data_dir=user_data_dir, **{alias: str(video_dir)}
- )
- )
+ # Create profile without the alias first
+ browser_profile = BrowserProfile(headless=True, disable_security=True, user_data_dir=user_data_dir)
+
+ # Set the appropriate alias dynamically
+ setattr(browser_profile, alias, str(video_dir))
+
+ browser_session = BrowserSession(browser_profile=browser_profile)
await browser_session.start()
try:
await browser_session.navigate(httpserver_url)
@@ -256,11 +259,13 @@ class TestBrowserProfileRecordings:
har_path = test_dir / f'network_{context_type}_{alias}.har'
user_data_dir = None if context_type == 'incognito' else str(test_dir / f'user_data_har_{alias}')
- browser_session = BrowserSession(
- browser_profile=BrowserProfile(
- headless=True, disable_security=True, user_data_dir=user_data_dir, **{alias: str(har_path)}
- )
- )
+ # Create profile without the alias first
+ browser_profile = BrowserProfile(headless=True, disable_security=True, user_data_dir=user_data_dir)
+
+ # Set the appropriate alias dynamically
+ setattr(browser_profile, alias, str(har_path))
+
+ browser_session = BrowserSession(browser_profile=browser_profile)
await browser_session.start()
try:
await browser_session.navigate(httpserver_url)
diff --git a/tests/ci/test_controller.py b/tests/ci/test_controller.py
index 08368fe58..c802033a9 100644
--- a/tests/ci/test_controller.py
+++ b/tests/ci/test_controller.py
@@ -115,6 +115,7 @@ class TestControllerIntegration:
# Verify the result
assert isinstance(result, ActionResult)
+ assert result.extracted_content is not None
assert f'Navigated to {base_url}/page1' in result.extracted_content
# Verify the current page URL
@@ -142,6 +143,7 @@ class TestControllerIntegration:
# Verify the result
assert isinstance(result, ActionResult)
+ assert result.extracted_content is not None
assert 'Scrolled down' in result.extracted_content
# Create scroll up action
@@ -155,6 +157,7 @@ class TestControllerIntegration:
# Verify the result
assert isinstance(result, ActionResult)
+ assert result.extracted_content is not None
assert 'Scrolled up' in result.extracted_content
async def test_registry_actions(self, controller, browser_session):
@@ -210,6 +213,7 @@ class TestControllerIntegration:
# Verify the result
assert isinstance(result, ActionResult)
+ assert result.extracted_content is not None
assert 'Custom action executed with: test_value on' in result.extracted_content
assert f'{base_url}/page1' in result.extracted_content
@@ -264,6 +268,7 @@ class TestControllerIntegration:
result = await controller.act(InputTextActionModel(**input_action), browser_session)
# If successful, verify the result
assert isinstance(result, ActionResult)
+ assert result.extracted_content is not None
assert 'Input' in result.extracted_content
except Exception as e:
# If it fails due to DOM issues, that's expected in a test environment
@@ -355,6 +360,7 @@ class TestControllerIntegration:
# Verify the result
assert isinstance(result, ActionResult)
+ assert result.extracted_content is not None
assert 'Navigated back' in result.extracted_content
# Add another delay to allow the navigation to complete
@@ -477,6 +483,7 @@ class TestControllerIntegration:
# Verify the result
assert isinstance(result, ActionResult)
+ assert result.extracted_content is not None
assert 'Searched for "Python web automation" in Google' in result.extracted_content
# For our test purposes, we just verify we're on some URL
@@ -510,6 +517,7 @@ class TestControllerIntegration:
# Verify the result
assert isinstance(result, ActionResult)
+ assert result.extracted_content is not None
assert success_done_message in result.extracted_content
assert result.success is True
assert result.is_done is True
@@ -525,6 +533,7 @@ class TestControllerIntegration:
# Verify the result
assert isinstance(result, ActionResult)
+ assert result.extracted_content is not None
assert failed_done_message in result.extracted_content
assert result.success is False
assert result.is_done is True
@@ -738,6 +747,7 @@ class TestControllerIntegration:
# Step 5: Verify the controller action result
assert result.error is None, f'Drag operation failed with error: {result.error}'
assert result.is_done is False
+ assert result.extracted_content is not None
assert '🖱️ Dragged from' in result.extracted_content
# Step 6: Verify the element was moved by checking its new parent
@@ -1040,6 +1050,7 @@ class TestControllerIntegration:
assert isinstance(result, ActionResult)
# Core logic validation: Verify all options are returned
+ assert result.extracted_content is not None
for option in expected_options[1:]: # Skip the placeholder option
assert option['text'] in result.extracted_content, f"Option '{option['text']}' not found in result content"
@@ -1137,6 +1148,7 @@ class TestControllerIntegration:
assert isinstance(result, ActionResult)
# Core logic validation: Verify selection was successful
+ assert result.extracted_content is not None
assert 'selected option' in result.extracted_content.lower()
assert 'Second Option' in result.extracted_content
@@ -1239,6 +1251,7 @@ class TestControllerIntegration:
assert result.error is None, f'Expected no error but got: {result.error}'
# Core logic validation: Verify click was successful
+ assert result.extracted_content is not None
assert f'Clicked button with index {button_index}' in result.extracted_content, (
f'Expected click confirmation in result content, got: {result.extracted_content}'
)