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
fixing structure and agents
Gregor Žunič588d517db8c2
diff --git a/src/actions/browser_actions.py b/src/actions/browser_actions.pyindex 1d4af4d81..d537b6f71 100644--- a/src/actions/browser_actions.py+++ b/src/actions/browser_actions.py@@ -1,11 +1,11 @@import time+from typing import Dict, Optional, Union+from pydantic import BaseModelfrom 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@@ -20,9 +20,11 @@ class Action(BaseModel):action: strparams: Optional[ActionParams] = None--class SelectorMap(BaseModel):- __root__: Dict[int, str]+ @property+ def is_valid(self) -> bool:+ if self.action == 'click':+ return self.params is not None and self.params.id is not None+ return Trueclass BrowserActions:@@ -31,39 +33,44 @@ class BrowserActions:self.wait = WebDriverWait(driver, 10)self.selector_map: Dict[int, str] = {}- def update_selector_map(self, selector_map: Union[Dict[int, str], SelectorMap]):+ def update_selector_map(self, selector_map: Dict[int, str]):"""Update the current selector map"""- if isinstance(selector_map, SelectorMap):- self.selector_map = selector_map.__root__- else:- self.selector_map = selector_map-- 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)+ self.selector_map = selector_map- print(action.dict().keys())+ def execute_action(self, action: Action, selector_map: Dict[int, str]):+ print(action.model_dump().keys())+ print(action.model_dump_json())action_name = action.actionself.update_selector_map(selector_map)- params = action.params.dict() if action.params else {}+ # params = action.params.model_dump() if action.params else {}if action_name == 'search_google':- self.search_google(params['query'])+ if action.params and action.params.query:+ self.search_google(action.params.query)+ else:+ raise Exception('Query is required for search_google action')elif action_name == 'nothing':passelif action_name == 'go_to_url':- self.go_to_url(params['url'])+ if action.params and action.params.url:+ self.go_to_url(action.params.url)+ else:+ raise Exception('Url is required for go_to_url action')elif action_name == 'go_back':self.go_back()elif action_name == 'done':return Trueelif action_name == 'input':- self.input_text_by_index(params['id'], params['text'])+ if action.params and action.params.id and action.params.text:+ self.input_text_by_index(action.params.id, action.params.text)+ else:+ raise Exception('Id and text are required for input action')elif action_name == 'click':- self.click_element_by_index(params['id'])+ if action.params and action.params.id:+ self.click_element_by_index(action.params.id)+ else:+ raise Exception('Id is required for click action')# elif action_name == 'accept_cookies':# self.driver.accept_cookies()else:diff --git a/src/agent_interface/planing_agent.py b/src/agent_interface/planing_agent.pyindex 0ebaed2c0..8166eb97d 100644--- a/src/agent_interface/planing_agent.py+++ b/src/agent_interface/planing_agent.py@@ -1,54 +1,51 @@-import json-import os-from typing import Dict, List-from dotenv import load_dotenv-from openai import OpenAIfrom tokencost import calculate_prompt_cost, count_string_tokens-from src.actions.browser_actions import Action-from src.llm.service import LLM+from src.actions.browser_actions import Action+from src.llm.service import LLM, AvailableModelclass PlaningAgent:- def __init__(self, task: str, default_actions: str):+ def __init__(self, task: str, default_actions: str, model: AvailableModel):load_dotenv()- # self.client = OpenAI(api_key=os.getenv('OPENAI_API_KEY'))- self.model = 'gpt-4o'+ self.model = modelself.llm = LLM(model=self.model)self.messages = [{'role': 'system', 'content': self.get_system_prompt(task, default_actions)}]- async def chat(self, task: str, skip_call: bool = False) -> Dict:+ async def chat(self, task: str, skip_call: bool = False) -> Action:# TODO: include state, actions, etc.# select next functions to callmessages = self.messages + [{'role': 'user', 'content': task}]- # Calculate total cost for all messages- total_cost = calculate_prompt_cost(messages, self.model)- total_tokens = count_string_tokens(' '.join([m['content'] for m in messages]), self.model)- print(- 'Total prompt cost: ',- f'${total_cost:,.2f}',- 'Total tokens: ',- f'{total_tokens:,}',- )+ try:+ # Calculate total cost for all messages+ total_cost = calculate_prompt_cost(messages, self.model)+ total_tokens = count_string_tokens(+ ' '.join([m['content'] for m in messages]), self.model+ )+ print(+ 'Total prompt cost: ',+ f'${total_cost:,.2f}',+ 'Total tokens: ',+ f'{total_tokens:,}',+ )+ except Exception as e:+ print(f'Error calculating prompt cost: {e}')if skip_call:- return {'action': 'nothing'}+ return Action(action='nothing')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'}- # )+ self.messages.append({'role': 'user', 'content': '... redacted previous state ...'})# Only append the output message- self.messages.append({'role': 'assistant', 'content': response.choices[0].message.content})+ self.messages.append({'role': 'assistant', 'content': response.model_dump_json()})- return json.loads(response.choices[0].message.content)+ return responsedef get_system_prompt(self, task: str, default_actions: str) -> str:"""@@ -77,7 +74,7 @@ class PlaningAgent:1:<a href="/test">Link text</a>2:Some visible text content- To interact with elements, use their index number in the click() or input() actions.+ To interact with elements, use their index number in the click() or input() actions. Make 100% sure that the index is ALWAYS present if you use the click() or input() actions.Each element has a unique index that can be used to interact with it.Provide your next action based on the available actions and visible elements.diff --git a/src/dom/service.py b/src/dom/service.pyindex 34ef7152b..04494d602 100644--- a/src/dom/service.py+++ b/src/dom/service.py@@ -9,7 +9,7 @@ from selenium import webdriverclass ProcessedDomContent(BaseModel):output_string: str- selector_map: dict+ selector_map: dict[int, str]class DomService:@@ -66,7 +66,7 @@ class DomService:candidate_elements.append(element)# Process candidates- selector_map = {}+ selector_map: dict[int, str] = {}output_string = ''for index, element in enumerate(candidate_elements):diff --git a/src/dom/tests/service_test.py b/src/dom/tests/service_test.pyindex a4d422ca6..813e49726 100644--- a/src/dom/tests/service_test.py+++ b/src/dom/tests/service_test.py@@ -18,4 +18,4 @@ def test_process_html_file():# Add assertions based on expected content of page.htmlprint(f'Processed DOM content: {result.output_string}')- # print(f'Selector map: {result.selector_map}')+ print(f'Selector map: {result.selector_map}')diff --git a/src/llm/tests/service_test.py b/src/llm/tests/service_test.pyindex 3b57be9bb..6b6bc5baa 100644--- a/src/llm/tests/service_test.py+++ b/src/llm/tests/service_test.py@@ -4,9 +4,9 @@ import pytestfrom src.llm.service import LLM[email protected](reason='openai costs')+# @pytest.mark.skip(reason='openai costs')async def test_completion():- messages = [{'role': 'user', 'content': 'List 5 important events in the XIX century'}]+ messages = [{'role': 'user', 'content': 'List 2 important events in the XIX century'}]class CalendarEvent(BaseModel):name: str@@ -16,7 +16,8 @@ async def test_completion():class EventsList(BaseModel):events: list[CalendarEvent]- llm = LLM(model='gpt-4o-2024-08-06')+ # llm = LLM(model='gpt-4o-2024-08-06')+ llm = LLM(model='claude-3-5-sonnet-20240620')resp = await llm.create_chat_completion(messages, EventsList)diff --git a/src/state_manager/state.py b/src/state_manager/state.pyindex 76f4a7ec1..fba75c5f2 100644--- a/src/state_manager/state.py+++ b/src/state_manager/state.py@@ -9,14 +9,14 @@ from src.dom.service import DomServiceclass ProcessedContent(BaseModel):output_string: str- selector_map: Dict[str, str]+ selector_map: Dict[int, str]class PageState(BaseModel):current_url: strpage_title: strinteractable_elements: str- selector_map: Dict[str, str]+ selector_map: Dict[int, str]class StateManager:diff --git a/src/tests/test_kayak_search.py b/src/tests/test_kayak_search.pyindex ec7eeb3bf..52caf970e 100644--- a/src/tests/test_kayak_search.py+++ b/src/tests/test_kayak_search.py@@ -1,5 +1,5 @@import time-import unittest+import pytestfrom src.actions.browser_actions import BrowserActionsfrom src.agent_interface.planing_agent import PlaningAgent@@ -8,54 +8,53 @@ from src.state_manager.state import StateManagerfrom src.state_manager.utils import save_formatted_html-class TestKayakSearch(unittest.TestCase):- def setUp(self):- self.driver = DriverService().get_driver()- self.actions = BrowserActions(self.driver)- self.state_manager = StateManager(self.driver)+async def setup():+ driver = DriverService().get_driver()+ actions = BrowserActions(driver)+ state_manager = StateManager(driver)+ yield driver, actions, state_manager+ driver.quit()- def tearDown(self):- self.driver.quit()- def test_kayak_flight_search(self):- # Define the task- task = 'Go to directly to the url https://www.kayak.ch/ and look there for flights from Zurich to New York for Nov 5th, 2024 for 2 people'+async def test_kayak_flight_search(setup):+ driver, actions, state_manager = setup- default_actions = self.actions.get_default_actions()- print(f'Default actions: {default_actions}')+ # Define the task+ task = 'Go to directly to the url ebay.com find a newly listed pre-owned man nike shoe in size 9 with free local pickup under 75 dollars.'- agent = PlaningAgent(task, default_actions)- url_history = []+ default_actions = actions.get_default_actions()+ print(f'Default actions: {default_actions}')- # Main interaction loop- max_steps = 50- for i in range(max_steps):- # Get current state- # input('\n\n\nPress Enter to continue...')+ agent = PlaningAgent(task, str(default_actions), 'gpt-4o')+ url_history = []- current_state = self.state_manager.get_current_state()- save_formatted_html(current_state['interactable_elements'], f'current_state_{i}.html')- print(f'Current state map: {current_state["selector_map"]}')- # save_markdown(current_state["main_content"], f"current_state_{i}.md")- # Get next action from agent- url_history.append(self.driver.current_url)- text = f'Elements: {current_state["interactable_elements"]}, Url history: {url_history}'- print(f'\n{text}\n')+ # Main interaction loop+ max_steps = 50+ for i in range(max_steps):+ # Get current state+ # input('\n\n\nPress Enter to continue...')- action = agent.chat(text, skip_call=False)- print(f'Selected action: {action}')+ current_state = state_manager.get_current_state()+ save_formatted_html(current_state.interactable_elements, f'current_state_{i}.html')+ print(f'Current state map: {current_state.selector_map}')+ # save_markdown(current_state["main_content"], f"current_state_{i}.md")+ # Get next action from agent+ url_history.append(driver.current_url)+ text = f'Elements: {current_state.interactable_elements}, Url history: {url_history}'+ print(f'\n{text}\n')- out = self.actions.execute_action(action, current_state['selector_map'])- if out:- print('Task completed')- break+ action = await agent.chat(text, skip_call=False)+ print(f'Selected action: {action}')- # Wait for 1 second- time.sleep(1)+ out = actions.execute_action(action, current_state.selector_map)+ if out:+ print('Task completed')+ break- else:- self.fail('Failed to complete flight search task in maximum steps')+ # Wait for 1 second+ time.sleep(1)--if __name__ == '__main__':- unittest.main()+ else:+ assert False, 'Failed to complete flight search task in maximum steps'