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
Zürich to Bali flight search works
magmueller237e7aa78298
diff --git a/src/actions/browser_actions.py b/src/actions/browser_actions.pyindex d537b6f71..83f5e458e 100644--- a/src/actions/browser_actions.py+++ b/src/actions/browser_actions.py@@ -19,6 +19,8 @@ class ActionParams(BaseModel):class Action(BaseModel):action: strparams: Optional[ActionParams] = None+ goal: str+ valuation_previous_goal: str@propertydef is_valid(self) -> bool:@@ -38,8 +40,8 @@ class BrowserActions:self.selector_map = selector_mapdef execute_action(self, action: Action, selector_map: Dict[int, str]):- print(action.model_dump().keys())- print(action.model_dump_json())+ # print(action.model_dump().keys())+ print(action.model_dump_json(indent=4))action_name = action.actionself.update_selector_map(selector_map)@@ -85,10 +87,10 @@ class BrowserActions:raise Exception(f'Element index {index} not found in selector map')xpath = self.selector_map[int(index)]- print(f'Trying to click element with xpath: {xpath}')+ # print(f'Trying to click element with xpath: {xpath}')# Wait for any overlays/popups to disappear- time.sleep(2) # Brief wait for page to stabilize+ time.sleep(0.5) # Brief wait for page to stabilizetry:# Try multiple strategies to find the elementdiff --git a/src/agent_interface/planing_agent.py b/src/agent_interface/planing_agent.pyindex 207b2a836..b58cd0eac 100644--- a/src/agent_interface/planing_agent.py+++ b/src/agent_interface/planing_agent.py@@ -10,21 +10,23 @@ class PlaningAgent:load_dotenv()self.model = modelself.llm = LLM(model=self.model)- self.messages = [+ self.system_prompt = [{'role': 'system', 'content': self.get_system_prompt(task, default_actions)}]+ self.messages_all = []+ self.messages = []async def chat(self, task: str, skip_call: bool = False) -> Action:# TODO: include state, actions, etc.# select next functions to call- messages = self.messages + [{'role': 'user', 'content': task}]+ input_messages = self.system_prompt + self.messages + [{'role': 'user', 'content': task}]try:# Calculate total cost for all messages- total_cost = calculate_prompt_cost(messages, self.model)+ total_cost = calculate_prompt_cost(input_messages, self.model)total_tokens = count_string_tokens(- ' '.join([m['content'] for m in messages]), self.model+ ' '.join([m['content'] for m in input_messages]), self.model)print('Total prompt cost: ',@@ -38,13 +40,17 @@ class PlaningAgent:if skip_call:return Action(action='nothing')- response = await self.llm.create_chat_completion(messages, Action)+ response = await self.llm.create_chat_completion(input_messages, Action)- self.messages.append({'role': 'user', 'content': '... redacted previous state ...'})+ self.messages.append({'role': 'user', 'content': '... execute action ...'})# Only append the output messageself.messages.append({'role': 'assistant', 'content': response.model_dump_json()})+ # keep newest 20 messages+ if len(self.messages) > 20:+ self.messages = self.messages[-20:]+return responsedef get_system_prompt(self, task: str, default_actions: str) -> str:@@ -60,7 +66,7 @@ class PlaningAgent:"""# System prompts for the agentoutput_format = """- {"action": "action_name", "params": {"param_name": "param_value"}, "goal": "short description what you want to achieve", "valuation_previous_goal": "1-10 how confident you are that you achieved your previous goal. If its the first action, put 0."}+ {"action": "action_name", "params": {"param_name": "param_value"}, "goal": "short description what you want to achieve", "valuation_previous_goal": "Success if completed, else short sentence of why not successful."}"""AGENT_PROMPT = f"""@@ -82,7 +88,7 @@ class PlaningAgent:Provide your next action based on the available actions and visible elements.Validate if the previous goal is achieved, if not, try to achieve it with the next action.- If you get stuck, try to find a new element that can help you achieve your goal. Or go back to try it differently.+ If you get stuck, try to find a new element that can help you achieve your goal or if persistent, go back or reload the page.Respond with a valid JSON object containing the action and any required parameters and your current goal of this action.Response format:diff --git a/src/tests/test_kayak_search.py b/src/tests/test_kayak_search.pyindex 25c2b8a29..54220da69 100644--- a/src/tests/test_kayak_search.py+++ b/src/tests/test_kayak_search.py@@ -24,7 +24,7 @@ async def test_kayak_flight_search(setup):# 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.'- task = 'Go to directly to the url kayak.com find a flight from Zürich to Kirgistan on 2024-11-25 with return on 2024-12-09 for 2 people.'+ task = 'Go to directly to the url kayak.com find a flight from Zürich to Bali on 2024-11-25 with return on 2024-12-09 for 2 people.'default_actions = actions.get_default_actions()print(f'Default actions: {default_actions}')@@ -36,26 +36,27 @@ async def test_kayak_flight_search(setup):for i in range(max_steps):# Get current state# input('\n\n\nPress Enter to continue...')-+ print(f'Step {i}')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}')+ # print(f'Current state map: {current_state.selector_map}')# save_markdown(current_state["main_content"], f"current_state_{i}.md")# Get next action from agenturl_history.append(driver.current_url)text = f'Elements: {current_state.interactable_elements}, Url history: {url_history}'- print(f'\n{text}\n')+ # print(f'\n{text}\n')action = await agent.chat(text, skip_call=False)- print(f'Selected action: {action}')+ # print(f'Selected action: {action}')out = actions.execute_action(action, current_state.selector_map)+ print('')if out:print('Task completed')break# Wait for 1 second- time.sleep(1)+ time.sleep(0.5)else:assert False, 'Failed to complete flight search task in maximum steps'