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
Search https://www.kayak.ch/ workds
magmueller8b2404479ee3
diff --git a/src/actions/browser_actions.py b/src/actions/browser_actions.pyindex 0817988f4..b21239855 100644--- a/src/actions/browser_actions.py+++ b/src/actions/browser_actions.py@@ -9,6 +9,23 @@ class BrowserActions:self.driver = driverself.wait = WebDriverWait(driver, 10)+ def execute_action(self, action: dict):+ print(action.keys())+ action_name = action["action"]+ params = action["params"]++ if action_name == "search_google":+ self.search_google(params["query"])+ elif action_name == "go_to_url":+ self.go_to_url(params["url"])+ elif action_name == "go_back":+ self.go_back()+ elif action_name == "done":+ return True+ else:+ raise Exception(f"Action {action_name} not found")++ # default actionsdef search_google(self, query: str):"""Performs a Google search with the provided query.@@ -27,6 +44,13 @@ class BrowserActions:"""self.driver.get(url)+ def go_back(self):+ """+ Navigates back in the browser history.+ """+ self.driver.back()++ # specific actionsdef click_element(self, identifier: dict):"""Clicks an element identified by attributes.@@ -63,3 +87,11 @@ class BrowserActions:except:continueraise Exception("Element not found with provided identifiers")++ def get_default_actions(self) -> dict[str, str]:+ return {+ "search_google": "query: string",+ "go_to_url": "url: string",+ "done": "",+ "go_back": ""+ }diff --git a/src/agent_interface/agent.py b/src/agent_interface/agent.pydeleted file mode 100644index b6e8dc4ee..000000000--- a/src/agent_interface/agent.py+++ /dev/null@@ -1,33 +0,0 @@-from typing import Dict, List, Optional-import json---class Agent:- def __init__(self):- self.current_state = None- self.available_actions = None- self.task = None- self.context = None- self.task_progress = []-- def set_task(self, task: Dict):- """- Sets the task for the agent to complete.-- Args:- task (Dict): Task description with type and parameters- """- self.task = task- self.task_progress = []-- def receive_state(self, state: Dict, actions: List):- """- Receives the current state and possible actions.-- Args:- state (Dict): Current browser state including URL and interactable elements- actions (List): List of possible actions that can be taken- """- self.current_state = state- self.available_actions = actions- self.task_progress.append(state)diff --git a/src/agent_interface/planing_agent.py b/src/agent_interface/planing_agent.pynew file mode 100644index 000000000..3fdc8264a--- /dev/null+++ b/src/agent_interface/planing_agent.py@@ -0,0 +1,47 @@+from typing import Dict, List, Optional+import json+import os+from openai import OpenAI+from dotenv import load_dotenv+++class PlaningAgent:+ def __init__(self, task: str, default_actions: str):+ load_dotenv()+ self.client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))+ self.model = "gpt-4o"+ self.messages = [{"role": "system", "content": self.get_system_prompt(task, default_actions)}]++ def chat(self, task: str) -> Dict:+ # TODO: include state, actions, etc.++ # select next functions to call+ self.messages.append({"role": "user", "content": task})+ response = self.client.chat.completions.create(+ model=self.model,+ messages=self.messages,+ response_format={"type": "json_object"}+ )+ self.messages.append(response.choices[0].message)+ # parse the response+ return json.loads(response.choices[0].message.content)++ def get_system_prompt(self, task: str, default_actions: str) -> str:+ # System prompts for the agent+ output_format = """+ {"action": "action_name", "params": {"param_name": "param_value"}}+ """++ AGENT_PROMPT = f"""+ You are a web scraping agent. Your task is to control the browser where, for every step,+ you get the current state and a list of actions you can take as dictionary. You have to select the next action in json format:+ {output_format}++ Your task is:+ {task}++ Available default actions:+ {default_actions}+ """++ return AGENT_PROMPTdiff --git a/src/agent_interface/prompts.py b/src/agent_interface/prompts.pydeleted file mode 100644index 3890f8f48..000000000--- a/src/agent_interface/prompts.py+++ /dev/null@@ -1,21 +0,0 @@-# System prompts for the agent-AGENT_PROMPT = """-You are a web scraping agent. Your task is to control the browser where, for every step,-you get the current state and a list of actions you can take.--Your task is:-{task}--In every step, please only control the web browser with actions.-Actions can also give you back follow-up questions about the state of the website-if your instructions are ambiguous.-"""--# State representation prompt-STATE_PROMPT = """-Current browser state:-{- "state": {state},- "actions": {actions}-}-"""diff --git a/src/state_manager/state.py b/src/state_manager/state.pyindex a2450fd8d..f7330b0ea 100644--- a/src/state_manager/state.py+++ b/src/state_manager/state.py@@ -18,9 +18,17 @@ class StateManager:"""html_content = self.driver.page_sourcecleaned_html = cleanup_html(html_content)+ functions = self.get_functions()return {"current_url": self.driver.current_url,"page_title": self.driver.title,- "interactable_elements": cleaned_html+ "interactable_elements": cleaned_html,+ "functions": functions}++ def get_functions(self) -> List[Dict]:+ """+ Retrieves available functions from cleaned HTML.+ """+ return []diff --git a/src/tests/test_kayak_search.py b/src/tests/test_kayak_search.pyindex ae91dd241..353cf9fd4 100644--- a/src/tests/test_kayak_search.py+++ b/src/tests/test_kayak_search.py@@ -2,6 +2,7 @@ import unittestfrom src.utils.selenium_utils import setup_selenium_driverfrom src.actions.browser_actions import BrowserActionsfrom src.state_manager.state import StateManager+from src.agent_interface.planing_agent import PlaningAgentclass TestKayakSearch(unittest.TestCase):@@ -13,6 +14,36 @@ class TestKayakSearch(unittest.TestCase):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"++ default_actions = self.actions.get_default_actions()+ print(f"Default actions: {default_actions}")++ agent = PlaningAgent(task, default_actions)++ # Main interaction loop+ max_steps = 10+ for _ in range(max_steps):+ # Get current state+ current_state = self.state_manager.get_current_state()++ # Get next action from agent+ text = f"Current state: {current_state}"+ print(f"\n{text}\n")++ action = agent.chat(text)+ print(f"Selected action: {action}")++ out = self.actions.execute_action(action)+ if out:+ print("Task completed")+ break++ else:+ self.fail("Failed to complete flight search task in maximum steps")+if __name__ == '__main__':unittest.main()