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
added llms
Gregor Žunič28edd02baa5a
diff --git a/pyproject.toml b/pyproject.tomlindex d2a1b924a..69d482044 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -12,4 +12,4 @@ line-length = 100[tool.ruff.format]quote-style = "single"indent-style = "tab"-docstring-code-format = true\ No newline at end of file+docstring-code-format = truediff --git a/pytest.ini b/pytest.ininew file mode 100644index 000000000..d280de047--- /dev/null+++ b/pytest.ini@@ -0,0 +1,2 @@+[pytest]+asyncio_mode = auto\ No newline at end of filediff --git a/src/actions/action_validator.py b/src/actions/action_validator.pyindex f95e5db7b..32d313e06 100644--- a/src/actions/action_validator.py+++ b/src/actions/action_validator.py@@ -17,7 +17,7 @@ class ActionValidator:bool: True if action was successful, False otherwise"""try:- pass+ return Trueexcept (TimeoutException, WebDriverException):return False@@ -33,4 +33,4 @@ class ActionValidator:bool: True if action is ambiguous, False otherwise"""# Implementation will use LLM to check for ambiguity- pass+ return Falsediff --git a/src/actions/browser_actions.py b/src/actions/browser_actions.pyindex da65c02eb..1d4af4d81 100644--- a/src/actions/browser_actions.py+++ b/src/actions/browser_actions.py@@ -4,27 +4,51 @@ from selenium import webdriverfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support import expected_conditions as ECfrom selenium.webdriver.support.ui import WebDriverWait+from pydantic import BaseModel+from typing import Optional, Dict, Union+++# Pydantic Models+class ActionParams(BaseModel):+ query: Optional[str] = None+ url: Optional[str] = None+ id: Optional[int] = None+ text: Optional[str] = None+++class Action(BaseModel):+ action: str+ params: Optional[ActionParams] = None+++class SelectorMap(BaseModel):+ __root__: Dict[int, str]class BrowserActions:def __init__(self, driver: webdriver.Chrome):self.driver = driverself.wait = WebDriverWait(driver, 10)- self.selector_map = {} # Will store current selector map+ self.selector_map: Dict[int, str] = {}- def update_selector_map(self, selector_map: dict):+ def update_selector_map(self, selector_map: Union[Dict[int, str], SelectorMap]):"""Update the current selector map"""- self.selector_map = selector_map+ if isinstance(selector_map, SelectorMap):+ self.selector_map = selector_map.__root__+ else:+ self.selector_map = selector_map- def execute_action(self, action: dict, selector_map: dict):- print(action.keys())- action_name = action['action']+ def execute_action(self, action: Union[dict, Action], selector_map: Union[dict, SelectorMap]):+ if isinstance(action, dict):+ action = Action(**action)+ if isinstance(selector_map, dict):+ selector_map = SelectorMap(__root__=selector_map)++ print(action.dict().keys())+ action_name = action.actionself.update_selector_map(selector_map)- if 'params' in action:- params = action['params']- else:- params = {}+ params = action.params.dict() if action.params else {}if action_name == 'search_google':self.search_google(params['query'])diff --git a/src/agent_interface/planing_agent.py b/src/agent_interface/planing_agent.pyindex ec3821401..0ebaed2c0 100644--- a/src/agent_interface/planing_agent.py+++ b/src/agent_interface/planing_agent.py@@ -5,18 +5,22 @@ from typing import Dict, Listfrom dotenv import load_dotenvfrom openai import OpenAIfrom tokencost import calculate_prompt_cost, count_string_tokens+from src.actions.browser_actions import Action++from src.llm.service import LLMclass PlaningAgent:def __init__(self, task: str, default_actions: str):load_dotenv()- self.client = OpenAI(api_key=os.getenv('OPENAI_API_KEY'))+ # self.client = OpenAI(api_key=os.getenv('OPENAI_API_KEY'))self.model = 'gpt-4o'+ self.llm = LLM(model=self.model)self.messages = [{'role': 'system', 'content': self.get_system_prompt(task, default_actions)}]- def chat(self, task: str, skip_call: bool = False) -> Dict:+ async def chat(self, task: str, skip_call: bool = False) -> Dict:# TODO: include state, actions, etc.# select next functions to call@@ -35,9 +39,11 @@ class PlaningAgent:if skip_call:return {'action': 'nothing'}- response = self.client.chat.completions.create(- model=self.model, messages=messages, response_format={'type': 'json_object'}- )+ response = await self.llm.create_chat_completion(messages, Action)++ # response = self.client.chat.completions.create(+ # model=self.model, messages=messages, response_format={'type': 'json_object'}+ # )# Only append the output messageself.messages.append({'role': 'assistant', 'content': response.choices[0].message.content})diff --git a/src/dom/__tests__/__init__.py b/src/agent_interface/prompts.pysimilarity index 100%rename from src/dom/__tests__/__init__.pyrename to src/agent_interface/prompts.pydiff --git a/src/dom/service.py b/src/dom/service.pyindex 727f1fe36..34ef7152b 100644--- a/src/dom/service.py+++ b/src/dom/service.py@@ -285,6 +285,7 @@ class DomService:"""try:+ # todo: parse responses with pydanticis_visible = self.driver.execute_script(visibility_check)return bool(is_visible)except Exception:diff --git a/src/dom/tests/__init__.py b/src/dom/tests/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/src/dom/__tests__/service_test.py b/src/dom/tests/service_test.pysimilarity index 81%rename from src/dom/__tests__/service_test.pyrename to src/dom/tests/service_test.pyindex 722a50dda..a4d422ca6 100644--- a/src/dom/__tests__/service_test.py+++ b/src/dom/tests/service_test.py@@ -1,12 +1,11 @@-import osimport timefrom src.dom.service import DomService-from src.utils.selenium_utils import setup_selenium_driver+from src.driver.service import DriverServicedef test_process_html_file():- driver = setup_selenium_driver()+ driver = DriverService().get_driver()driver.get('https://www.kayak.ch')# driver.get('https://example.com/')diff --git a/src/driver/service.py b/src/driver/service.pynew file mode 100644index 000000000..db63fbaeb--- /dev/null+++ b/src/driver/service.py@@ -0,0 +1,40 @@+"""+Driver Service+"""++from selenium import webdriver+from selenium.webdriver.chrome.options import Options+from selenium.webdriver.chrome.service import Service+from webdriver_manager.chrome import ChromeDriverManager+++class DriverService:+ def __init__(self, headless: bool = False):+ self.headless = headless++ def get_driver(self) -> webdriver.Chrome:+ """+ Sets up and returns a Selenium WebDriver instance.++ Args:+ headless (bool): Whether to run browser in headless mode++ Returns:+ webdriver.Chrome: Configured Chrome WebDriver instance+ """+ # Configure Chrome options+ chrome_options = Options()+ if self.headless:+ chrome_options.add_argument('--headless')++ # Disable automation flags+ chrome_options.add_argument('--disable-blink-features=AutomationControlled')+ chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])+ chrome_options.add_experimental_option('useAutomationExtension', False)++ # Initialize the Chrome driver+ driver = webdriver.Chrome(+ service=Service(ChromeDriverManager().install()), options=chrome_options+ )++ return driverdiff --git a/src/llm/service.py b/src/llm/service.pynew file mode 100644index 000000000..efb472a91--- /dev/null+++ b/src/llm/service.py@@ -0,0 +1,46 @@+import logging+from typing import List, Literal, TypeVar++from litellm import LiteLLM, acompletion+from pydantic import BaseModel++logger = logging.getLogger(__name__)+logger.setLevel(logging.INFO)+++AvailableModel = Literal[+ 'gpt-4o',+ 'gpt-4o-mini',+ 'gpt-4o-2024-08-06',+ 'claude-3-5-sonnet-latest',+ 'claude-3-5-sonnet-20241022',+ 'claude-3-5-sonnet-20240620',+]+++class ChatCompletionResponseMessage(BaseModel):+ role: Literal['user', 'assistant', 'system']+ content: str+++ResponseModel = TypeVar('ResponseModel', bound=BaseModel)+++class LLM:+ def __init__(self, model: AvailableModel):+ self.logger = logger+ self.model = model+ self.llm = LiteLLM()++ async def create_chat_completion(+ self,+ messages: list,+ response_model: type[ResponseModel],+ ) -> ResponseModel:+ response = await acompletion(+ self.model, messages, response_format=response_model, stream=False+ )+ content: str = response.choices[0].message.content # type: ignore+ # Access the completion content directly from the response++ return response_model.model_validate_json(content)diff --git a/src/llm/tests/service_test.py b/src/llm/tests/service_test.pynew file mode 100644index 000000000..3b57be9bb--- /dev/null+++ b/src/llm/tests/service_test.py@@ -0,0 +1,23 @@+from pydantic import BaseModel+import pytest++from src.llm.service import LLM++[email protected](reason='openai costs')+async def test_completion():+ messages = [{'role': 'user', 'content': 'List 5 important events in the XIX century'}]++ class CalendarEvent(BaseModel):+ name: str+ date: str+ participants: list[str]++ class EventsList(BaseModel):+ events: list[CalendarEvent]++ llm = LLM(model='gpt-4o-2024-08-06')++ resp = await llm.create_chat_completion(messages, EventsList)++ print('Received={}'.format(resp))diff --git a/src/state_manager/state.py b/src/state_manager/state.pyindex 0d0b49d15..76f4a7ec1 100644--- a/src/state_manager/state.py+++ b/src/state_manager/state.py@@ -1,32 +1,44 @@from typing import Dict, Listimport requests+from pydantic import BaseModelfrom selenium import webdriver-from selenium.webdriver.common.by import Byfrom src.dom.service import DomService+class ProcessedContent(BaseModel):+ output_string: str+ selector_map: Dict[str, str]+++class PageState(BaseModel):+ current_url: str+ page_title: str+ interactable_elements: str+ selector_map: Dict[str, str]++class StateManager:def __init__(self, driver: webdriver.Chrome):self.driver = driverself.dom_service = DomService(driver)- def get_current_state(self) -> Dict:+ def get_current_state(self) -> PageState:"""Retrieves current URL and interactable elements from processed HTML.Returns:- Dict: Current state including URL, page title, interactable elements and selector map+ PageState: Current state including URL, page title, interactable elements and selector map"""processed_content = self.dom_service.get_current_state()- return {- 'current_url': self.driver.current_url,- 'page_title': self.driver.title,- 'interactable_elements': processed_content.output_string,- 'selector_map': processed_content.selector_map,- }+ return PageState(+ current_url=self.driver.current_url,+ page_title=self.driver.title,+ interactable_elements=processed_content.output_string,+ selector_map=processed_content.selector_map,+ )def get_functions(self) -> List[Dict]:"""@@ -34,7 +46,7 @@ class StateManager:"""return []- def get_main_content(self) -> str:+ def get_main_content(self) -> ProcessedContent:"""Retrieves main content from the page."""@@ -46,8 +58,11 @@ class StateManager:# Process content using DomServiceprocessed_content = self.dom_service._process_content(content)- return processed_content.output_string+ return ProcessedContent(+ output_string=processed_content.output_string,+ selector_map=processed_content.selector_map,+ )except Exception as e:print(f'Error getting main content: {e}')- return ''+ return ProcessedContent(output_string='', selector_map={})diff --git a/src/tests/test_kayak_search.py b/src/tests/test_kayak_search.pyindex 00953d00b..ec7eeb3bf 100644--- a/src/tests/test_kayak_search.py+++ b/src/tests/test_kayak_search.py@@ -3,14 +3,14 @@ import unittestfrom src.actions.browser_actions import BrowserActionsfrom src.agent_interface.planing_agent import PlaningAgent+from src.driver.service import DriverServicefrom src.state_manager.state import StateManager-from src.state_manager.utils import save_formatted_html, save_markdown-from src.utils.selenium_utils import setup_selenium_driver+from src.state_manager.utils import save_formatted_htmlclass TestKayakSearch(unittest.TestCase):def setUp(self):- self.driver = setup_selenium_driver(headless=False)+ self.driver = DriverService().get_driver()self.actions = BrowserActions(self.driver)self.state_manager = StateManager(self.driver)diff --git a/src/utils/selenium_utils.py b/src/utils/selenium_utils.pydeleted file mode 100644index 60ee09700..000000000--- a/src/utils/selenium_utils.py+++ /dev/null@@ -1,107 +0,0 @@-from selenium import webdriver-from selenium.webdriver.chrome.options import Options-from selenium.webdriver.chrome.service import Service-from selenium.webdriver.common.by import By-from selenium.webdriver.support import expected_conditions as EC-from selenium.webdriver.support.ui import WebDriverWait-from webdriver_manager.chrome import ChromeDriverManager---def setup_selenium_driver(headless: bool = False) -> webdriver.Chrome:- """- Sets up and returns a Selenium WebDriver instance.-- Args:- headless (bool): Whether to run browser in headless mode-- Returns:- webdriver.Chrome: Configured Chrome WebDriver instance- """- # Configure Chrome options- chrome_options = Options()- if headless:- chrome_options.add_argument('--headless')-- # Disable automation flags- chrome_options.add_argument('--disable-blink-features=AutomationControlled')- chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])- chrome_options.add_experimental_option('useAutomationExtension', False)-- # Initialize the Chrome driver- driver = webdriver.Chrome(- service=Service(ChromeDriverManager().install()), options=chrome_options- )-- # Add cookie acceptance function- def accept_cookies(driver):- """- More robust cookie acceptance function that tries multiple approaches- """- try:- # Common cookie accept button selectors- cookie_selectors = [- "button[id*='cookie-accept']",- "button[id*='accept-cookie']",- "button[class*='cookie-accept']",- "button[class*='accept-cookie']",- "[aria-label*='accept' i][role='button']",- "[aria-label*='cookie' i][role='button']",- "button:contains('Accept')",- "button:contains('Akzeptieren')",- "button:contains('Zustimmen')",- "button:contains('Alle akzeptieren')",- '#onetrust-accept-btn-handler',- '#accept-all-cookies',- '.accept-cookies',- '.accept-all-cookies',- ]-- wait = WebDriverWait(driver, 10)-- # Try each selector- for selector in cookie_selectors:- try:- # Try to find element by CSS selector- cookie_button = wait.until(- EC.element_to_be_clickable((By.CSS_SELECTOR, selector))- )- cookie_button.click()- return True- except:- try:- # Try to find element by XPath containing text- xpath = f"//*[contains(translate(text(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), '{selector.lower()}')]"- cookie_button = wait.until(EC.element_to_be_clickable((By.XPATH, xpath)))- cookie_button.click()- return True- except:- continue-- # Try finding iframe with cookie consent- iframes = driver.find_elements(By.TAG_NAME, 'iframe')- for iframe in iframes:- try:- driver.switch_to.frame(iframe)- for selector in cookie_selectors:- try:- cookie_button = wait.until(- EC.element_to_be_clickable((By.CSS_SELECTOR, selector))- )- cookie_button.click()- driver.switch_to.default_content()- return True- except:- continue- driver.switch_to.default_content()- except:- driver.switch_to.default_content()- continue-- except Exception as e:- print(f'Error accepting cookies: {str(e)}')- return False-- # Attach the function to the driver instance- driver.accept_cookies = lambda: accept_cookies(driver)-- return driver