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
renamed agent to controller
Gregor Žuničb5f8e46086e2
diff --git a/src/agent/service.py b/src/controller/service.pysimilarity index 74%rename from src/agent/service.pyrename to src/controller/service.pyindex 7a5a8765b..038083cd8 100644--- a/src/agent/service.py+++ b/src/controller/service.py@@ -1,10 +1,10 @@-from src.agent.views import AgentActionResult, AgentActions, AgentPageStatefrom src.browser.service import BrowserService+from src.controller.views import ControllerActionResult, ControllerActions, ControllerPageState-class AgentService:+class ControllerService:"""- Agent service that interacts with the browser.+ Controller service that interacts with the browser.Right now this is just a LLM friendly wrapper around the browser service.In the future we can add the functionality that this is a self-contained agent that can plan and act single steps.@@ -17,13 +17,13 @@ class AgentService:def __init__(self):self.browser = BrowserService()- def get_current_state(self, screenshot: bool = False) -> AgentPageState:+ def get_current_state(self, screenshot: bool = False) -> ControllerPageState:browser_state = self.browser.get_updated_state()screenshot_b64 = Noneif screenshot:screenshot_b64 = self.browser.take_screenshot()- return AgentPageState(+ return ControllerPageState(items=browser_state.items,url=browser_state.url,title=browser_state.title,@@ -31,7 +31,7 @@ class AgentService:screenshot=screenshot_b64,)- def act(self, action: AgentActions) -> AgentActionResult:+ def act(self, action: ControllerActions) -> ControllerActionResult:try:if action.search_google:self.browser.search_google(action.search_google.query)@@ -44,18 +44,18 @@ class AgentService:elif action.go_back:self.browser.go_back()elif action.done:- return AgentActionResult(done=True)+ return ControllerActionResult(done=True)elif action.click_element:self.browser.click_element_by_index(action.click_element.id)elif action.input_text:self.browser.input_text_by_index(action.input_text.id, action.input_text.text)elif action.extract_page_content:content = self.browser.extract_page_content()- return AgentActionResult(done=False, extracted_content=content)+ return ControllerActionResult(done=False, extracted_content=content)else:raise ValueError(f'Unknown action: {action}')- return AgentActionResult(done=False)+ return ControllerActionResult(done=False)except Exception as e:- return AgentActionResult(done=False, error=str(e))+ return ControllerActionResult(done=False, error=str(e))diff --git a/src/agent/views.py b/src/controller/views.pysimilarity index 67%rename from src/agent/views.pyrename to src/controller/views.pyindex 7489badbf..a0d49e5ed 100644--- a/src/agent/views.py+++ b/src/controller/views.py@@ -5,35 +5,35 @@ from pydantic import BaseModelfrom src.browser.views import BrowserState-class SearchGoogleAgentAction(BaseModel):+class SearchGoogleControllerAction(BaseModel):query: str-class GoToUrlAgentAction(BaseModel):+class GoToUrlControllerAction(BaseModel):url: str-class ClickElementAgentAction(BaseModel):+class ClickElementControllerAction(BaseModel):id: int-class InputTextAgentAction(BaseModel):+class InputTextControllerAction(BaseModel):id: inttext: str-class AgentActions(BaseModel):+class ControllerActions(BaseModel):"""- Agent actions you can use to interact with the agent.+ Controller actions you can use to interact."""- search_google: Optional[SearchGoogleAgentAction] = None- go_to_url: Optional[GoToUrlAgentAction] = None+ search_google: Optional[SearchGoogleControllerAction] = None+ go_to_url: Optional[GoToUrlControllerAction] = Nonenothing: Optional[Literal[True]] = Nonego_back: Optional[Literal[True]] = Nonedone: Optional[Literal[True]] = None- click_element: Optional[ClickElementAgentAction] = None- input_text: Optional[InputTextAgentAction] = None+ click_element: Optional[ClickElementControllerAction] = None+ input_text: Optional[InputTextControllerAction] = Noneextract_page_content: Optional[Literal[True]] = None@staticmethod@@ -68,11 +68,11 @@ class AgentActions(BaseModel):"""-class AgentActionResult(BaseModel):+class ControllerActionResult(BaseModel):done: boolextracted_content: Optional[str] = Noneerror: Optional[str] = None-class AgentPageState(BrowserState):+class ControllerPageState(BrowserState):screenshot: Optional[str] = Nonediff --git a/src/planning/prompts.py b/src/planning/prompts.pyindex edc4ac5cc..902f62646 100644--- a/src/planning/prompts.py+++ b/src/planning/prompts.py@@ -1,6 +1,6 @@from langchain_core.messages import HumanMessage, SystemMessage-from src.agent.views import AgentPageState+from src.controller.views import ControllerPageStateclass PlanningSystemPrompt:@@ -52,7 +52,7 @@ class PlanningSystemPrompt:class PlanningMessagePrompt:- def __init__(self, state: AgentPageState):+ def __init__(self, state: ControllerPageState):self.state = statedef get_user_message(self) -> HumanMessage:diff --git a/src/planning/service.py b/src/planning/service.pyindex edfb16b54..83c3cbaaa 100644--- a/src/planning/service.py+++ b/src/planning/service.py@@ -1,13 +1,11 @@from dotenv import load_dotenv-from langchain.output_parsers import PydanticOutputParserfrom langchain_core.language_models.chat_models import BaseChatModelfrom langchain_core.messages import AIMessage, BaseMessage, HumanMessage-from langchain_core.prompts import ChatPromptTemplate-from src.agent.service import AgentService-from src.agent.views import AgentActionResult, AgentPageState+from src.controller.service import ControllerService+from src.controller.views import ControllerActionResult, ControllerPageStatefrom src.planning.prompts import PlanningMessagePrompt, PlanningSystemPrompt-from src.planning.views import PlanningAgentAction+from src.planning.views import PlanningControllerActionload_dotenv()@@ -17,7 +15,7 @@ class PlaningService:self,task: str,llm: BaseChatModel,- agent: AgentService | None = None,+ controller: ControllerService | None = None,use_vision: bool = False,):"""@@ -28,7 +26,7 @@ class PlaningService:llm (AvailableModel): Model to be used.browser (BrowserService | None): You can reuse an existing browser service or (automatically) create a new one."""- self.agent = agent or AgentService()+ self.controller = controller or ControllerService()self.use_vision = use_vision@@ -41,19 +39,19 @@ class PlaningService:# self.messages_all: list[BaseMessage] = []self.messages: list[BaseMessage] = [system_prompt, first_message]- async def step(self) -> tuple[PlanningAgentAction, AgentActionResult]:- state = self.agent.get_current_state(screenshot=self.use_vision)+ async def step(self) -> tuple[PlanningControllerAction, ControllerActionResult]:+ state = self.controller.get_current_state(screenshot=self.use_vision)action = await self.get_next_action(state)if action.ask_human and action.ask_human.question:action = await self._take_human_input(action.ask_human.question)- result = self.agent.act(action)+ result = self.controller.act(action)input('continue? ...')return action, result- async def _take_human_input(self, question: str) -> PlanningAgentAction:+ async def _take_human_input(self, question: str) -> PlanningControllerAction:human_input = input(f'Human input required: {question}')self.messages.append(HumanMessage(content=human_input))@@ -62,14 +60,14 @@ class PlaningService:# | self.model# | PydanticOutputParser(pydantic_object=PlanningAgentAction)# )- structured_llm = self.llm.with_structured_output(PlanningAgentAction)- action: PlanningAgentAction = await structured_llm.ainvoke(self.messages) # type: ignore+ structured_llm = self.llm.with_structured_output(PlanningControllerAction)+ action: PlanningControllerAction = await structured_llm.ainvoke(self.messages) # type: ignoreself.messages.append(AIMessage(content=action.model_dump_json()))return action- async def get_next_action(self, state: AgentPageState) -> PlanningAgentAction:+ async def get_next_action(self, state: ControllerPageState) -> PlanningControllerAction:# TODO: include state, actions, etc.new_message = PlanningMessagePrompt(state).get_user_message()@@ -80,11 +78,11 @@ class PlaningService:else:print(f'model input: {new_message}')- structured_llm = self.llm.with_structured_output(PlanningAgentAction)+ structured_llm = self.llm.with_structured_output(PlanningControllerAction)# print(f'state:\n{state}')- response: PlanningAgentAction = await structured_llm.ainvoke(input_messages) # type: ignore+ response: PlanningControllerAction = await structured_llm.ainvoke(input_messages) # type: ignore# print('response', response)@@ -135,4 +133,4 @@ class PlaningService:return responsedef _get_action_description(self) -> str:- return PlanningAgentAction.description()+ return PlanningControllerAction.description()diff --git a/src/planning/views.py b/src/planning/views.pyindex e67c09752..cff76a0ba 100644--- a/src/planning/views.py+++ b/src/planning/views.py@@ -2,14 +2,14 @@ from typing import Optionalfrom pydantic import BaseModel-from src.agent.views import AgentActions+from src.controller.views import ControllerActionsclass AskHumanPlanningAgentAction(BaseModel):question: str-class PlanningAgentAction(AgentActions):+class PlanningControllerAction(ControllerActions):valuation_previous_goal: strgoal: str@@ -18,6 +18,6 @@ class PlanningAgentAction(AgentActions):@staticmethoddef description() -> str:return (- AgentActions.description()+ ControllerActions.description()+ '\n\nAsk human for help\nExample: {"ask_human": {"question": "To clarify ..."}}')diff --git a/src/tests/test_kayak_search.py b/src/tests/test_kayak_search.pyindex f5c09d912..9898cce23 100644--- a/src/tests/test_kayak_search.py+++ b/src/tests/test_kayak_search.py@@ -4,7 +4,7 @@ import osimport pytestfrom langchain_openai import ChatOpenAI-from src.agent.service import AgentService+from src.controller.service import ControllerServicefrom src.planning.service import PlaningService@@ -29,9 +29,9 @@ async def test_kayak_flight_search():task = 'go to kayak.com andfind a flight from Bali to Kirgistan on 2024-11-25 for 2 people one way.'run_folder = setup_run_folder('kayak_com_flight_search2')- agent = AgentService()+ controller = ControllerService()model = ChatOpenAI(model='gpt-4o')- planning_service = PlaningService(task, model, agent, use_vision=True)+ planning_service = PlaningService(task, model, controller, use_vision=True)print('\n' + '=' * 50)print('🚀 Starting flight search task')@@ -80,7 +80,7 @@ async def test_kayak_flight_search():# time.sleep(0.5)except KeyboardInterrupt:print('\n\nReceived interrupt, closing browser...')- agent.browser.close()+ controller.browser.close()raiseelse:print('\n' + '=' * 50)@@ -88,4 +88,4 @@ async def test_kayak_flight_search():print('=' * 50)assert False, 'Failed to complete task in maximum steps'finally:- agent.browser.close()+ controller.browser.close()