Skip to content

Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.

new version

Gregor Žuničaad4b04703ee
diff --git a/src/agent/views.py b/src/agent/views.py
index 35dd015f4..7489badbf 100644
--- a/src/agent/views.py
+++ b/src/agent/views.py
@@ -36,6 +36,37 @@ class AgentActions(BaseModel):
input_text: Optional[InputTextAgentAction] = None
extract_page_content: Optional[Literal[True]] = None
+ @staticmethod
+ def description() -> str:
+ """
+ Returns a human-readable description of available actions.
+ """
+ return """
+- Search Google with a query
+ Example: {"search_google": {"query": "weather today"}}
+
+- Navigate directly to a URL
+ Example: {"go_to_url": {"url": "https://abc.com"}}
+
+- Do nothing/wait
+ Example: {"nothing": true}
+
+- Go back to previous page
+ Example: {"go_back": true}
+
+- Mark task as complete
+ Example: {"done": true}
+
+- Click an element by its ID
+ Example: {"click_element": {"id": 1}}
+
+- Input text into an element by its ID
+ Example: {"input_text": {"id": 1, "text": "Hello world"}}
+
+- Extract and return the page content in markdown
+ Example: {"extract_page_content": true}
+"""
+
class AgentActionResult(BaseModel):
done: bool
diff --git a/src/browser/service.py b/src/browser/service.py
index b405288e0..df7a66e5d 100644
--- a/src/browser/service.py
+++ b/src/browser/service.py
@@ -90,7 +90,7 @@ class BrowserService:
def _get_driver(self) -> webdriver.Chrome:
if self.driver is None:
- raise BrowserException('Driver not initialized. Call `init()` first.')
+ self.driver = self.init()
return self.driver
def get_updated_state(self) -> BrowserState:
diff --git a/src/dom/views.py b/src/dom/views.py
index ae21113b4..cebd77550 100644
--- a/src/dom/views.py
+++ b/src/dom/views.py
@@ -10,6 +10,6 @@ class ProcessedDomContent(BaseModel):
items: list[DomContentItem]
selector_map: dict[int, str]
- def items_to_string(self) -> str:
+ def dom_items_to_string(self) -> str:
"""Convert the processed DOM content to HTML."""
return '\n'.join([item.text for item in self.items])
diff --git a/src/planning/prompts.py b/src/planning/prompts.py
index e27543a37..4b867d8da 100644
--- a/src/planning/prompts.py
+++ b/src/planning/prompts.py
@@ -1,10 +1,12 @@
-from langchain_core.messages import SystemMessage
+from langchain_core.messages import SystemMessage, HumanMessage
+
+from src.agent.views import AgentPageState
class PlanningSystemPrompt:
- def __init__(self, task: str, default_actions: str):
+ def __init__(self, task: str, default_action_description: str):
self.task = task
- self.default_actions = default_actions
+ self.default_action_description = default_action_description
def get_system_message(self) -> SystemMessage:
"""
@@ -14,9 +16,9 @@ class PlanningSystemPrompt:
str: Formatted system prompt
"""
# System prompts for the agent
- output_format = """
- {"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."}
- """
+ # output_format = """
+ # {"valuation_previous_goal": "Success if completed, else short sentence of why not successful.", "goal": "short description what you want to achieve", "action": "action_name", "params": {"param_name": "param_value"}}
+ # """
AGENT_PROMPT = f"""
You are an AI agent that helps users interact with websites.
@@ -25,17 +27,19 @@ class PlanningSystemPrompt:
This is how an input looks like:
1:Interactive element
- 3: <a href="https://www.example.de/"></a>
+ 3: <a href="https://www.ab.de/"></a>
9:<div>Interactive element</div>
Additional you get a list of previous actions and their results.
- Available actions:
- {self.default_actions}
+ Available actions (choose EXACTLY ONE, not 0 or 2):
+
+ {self.default_action_description}
In the beginning the list will be empty so you have to do google search or go to url.
To interact with elements, use their index number in the click() or text_input() actions. Make sure the index exists in the list of interactive elements.
If you need more than the interactive elements from the page you can use the extract_content action.
+ At every step you HAVE to choose EXACTLY ONE action.
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 if persistent, go back or reload the page.
@@ -43,15 +47,35 @@ class PlanningSystemPrompt:
You can send_user_text or ask_user for clarification if you are completely stuck.
Make sure after filling a field if you need to click a suggestion or if the field is already filled.
-
- Response format:
- {output_format}
-
"""
return SystemMessage(content=AGENT_PROMPT)
- # Remember:
- # 1. Always check if elements exist before trying to interact with them
- # 2. Use the exact index numbers shown in the elements list
- # 3. If you need to accept cookies, use the accept_cookies action first
- # 4. If you can't find what you're looking for, consider scrolling or navigating to a different page
+
+class PlanningMessagePrompt:
+ def __init__(self, state: AgentPageState):
+ self.state = state
+
+ def get_user_message(self) -> HumanMessage:
+ state_description = f"""
+Currently on url: {self.state.url}
+
+Interactive elements:
+{self.state.dom_items_to_string()}
+ """
+
+ if self.state.screenshot:
+ # Format message for vision model
+ return HumanMessage(
+ content=[
+ {'type': 'text', 'text': state_description},
+ {
+ 'type': 'image_url',
+ 'image_url': f'data:image/png;base64,{self.state.screenshot}',
+ },
+ ]
+ )
+
+ return HumanMessage(content=state_description)
+
+ def get_message_for_history(self) -> HumanMessage:
+ return HumanMessage(content=f'Currently on url: {self.state.url}')
diff --git a/src/planning/service.py b/src/planning/service.py
index e49c8c32b..6d87f5957 100644
--- a/src/planning/service.py
+++ b/src/planning/service.py
@@ -1,79 +1,97 @@
-import decimal
-
from dotenv import load_dotenv
+from langchain.output_parsers import PydanticOutputParser
from langchain_core.language_models.chat_models import BaseChatModel
-from langchain_core.messages import BaseMessage, HumanMessage, AIMessage
-from tokencost import calculate_all_costs_and_tokens
+from langchain_core.messages import AIMessage, BaseMessage, HumanMessage
from langchain_core.prompts import ChatPromptTemplate
-from src.browser.service import BrowserService
-
-# from src.llm.service import LLM, AvailableModel
-from src.planning.prompts import PlanningSystemPrompt
+from src.agent.service import AgentService
+from src.agent.views import AgentActionResult, AgentPageState
+from src.planning.prompts import PlanningMessagePrompt, PlanningSystemPrompt
from src.planning.views import PlanningAgentAction
-from src.state_manager.utils import encode_image, save_conversation
-
-from langchain.output_parsers import PydanticOutputParser
-
load_dotenv()
class PlaningService:
- def __init__(self, task: str, model: BaseChatModel, browser: BrowserService | None = None):
+ def __init__(
+ self,
+ task: str,
+ llm: BaseChatModel,
+ agent: AgentService | None = None,
+ use_vision: bool = False,
+ ):
"""
Planning service.
Args:
task (str): Task to be performed.
- model (AvailableModel): Model to be used.
+ llm (AvailableModel): Model to be used.
browser (BrowserService | None): You can reuse an existing browser service or (automatically) create a new one.
"""
- self.browser = browser or BrowserService()
-
- self.model = model
- # self.system_prompt = [
- # {'role': 'system', 'content': PlanningSystemPrompt(task, default_actions).get_prompt()}
- # ]
- self.messages_all: list[BaseMessage] = []
- self.messages: list[BaseMessage] = []
-
- async def chat(
- self, task: str, store_conversation: str = '', screenshot: str = ''
- ) -> PlanningAgentAction:
+ self.agent = agent or AgentService()
+
+ self.use_vision = use_vision
+
+ self.llm = llm
+ system_prompt = PlanningSystemPrompt(
+ task, self._get_action_description()
+ ).get_system_message()
+ first_message = HumanMessage(content=f'Your task is: {task}')
+
+ # 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()
+ 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)
+
+ return action, result
+
+ async def _take_human_input(self, question: str) -> PlanningAgentAction:
+ human_input = input(f'Human input required: {question}')
+
+ self.messages.append(HumanMessage(content=human_input))
+ # chain = (
+ # ChatPromptTemplate.from_messages(self.messages)
+ # | self.model
+ # | PydanticOutputParser(pydantic_object=PlanningAgentAction)
+ # )
+
+ structured_llm = self.llm.with_structured_output(PlanningAgentAction)
+ action: PlanningAgentAction = await structured_llm.ainvoke(self.messages) # type: ignore
+
+ self.messages.append(AIMessage(content=action.model_dump_json()))
+
+ return action
+
+ async def get_next_action(self, state: AgentPageState) -> PlanningAgentAction:
# TODO: include state, actions, etc.
- system_prompt = PlanningSystemPrompt(task, '{}').get_system_message()
- # select next functions to call
- if screenshot:
- # Format message for vision model
- new_message = HumanMessage(
- content=[
- {'type': 'text', 'text': task},
- {
- 'type': 'image_url',
- 'image_url': f'data:image/png;base64,{screenshot}',
- },
- ]
- )
+ new_message = PlanningMessagePrompt(state).get_user_message()
- else:
- new_message = HumanMessage(content=task)
+ input_messages = self.messages + [new_message]
+ structured_llm = self.llm.with_structured_output(PlanningAgentAction)
- input_messages = [system_prompt] + self.messages + [new_message]
+ print(state)
- # response = await self.model.gene(input_messages, Action)
+ input('continue? ...')
- prompt = ChatPromptTemplate.from_messages([system_prompt, *self.messages, new_message])
- chain = prompt | self.model | PydanticOutputParser(pydantic_object=PlanningAgentAction)
+ response: PlanningAgentAction = await structured_llm.ainvoke(input_messages) # type: ignore
- response: PlanningAgentAction = await chain.ainvoke({})
+ print('response', response)
- if store_conversation:
- # save conversation
- save_conversation(input_messages, response.model_dump_json(), store_conversation)
+ # if store_conversation:
+ # # save conversation
+ # save_conversation(input_messages, response.model_dump_json(), store_conversation)
# Only append the output message
+ history_new_message = PlanningMessagePrompt(state).get_message_for_history()
+ self.messages.append(history_new_message)
self.messages.append(AIMessage(content=response.model_dump_json()))
# try:
@@ -112,3 +130,6 @@ class PlaningService:
# self.messages = self.messages[-20:]
return response
+
+ def _get_action_description(self) -> str:
+ return PlanningAgentAction.description()
diff --git a/src/planning/views.py b/src/planning/views.py
index adbe549d4..e67c09752 100644
--- a/src/planning/views.py
+++ b/src/planning/views.py
@@ -10,4 +10,14 @@ class AskHumanPlanningAgentAction(BaseModel):
class PlanningAgentAction(AgentActions):
+ valuation_previous_goal: str
+ goal: str
+
ask_human: Optional[AskHumanPlanningAgentAction] = None
+
+ @staticmethod
+ def description() -> str:
+ return (
+ AgentActions.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.py
index 5e657ac1b..47fdb9206 100644
--- a/src/tests/test_kayak_search.py
+++ b/src/tests/test_kayak_search.py
@@ -1,14 +1,11 @@
import os
-import time
import pytest
-from src.browser.service import BrowserService
-from src.planning.service import PlaningService
-
-
-from src.state_manager.utils import encode_image, save_formatted_html
from langchain_openai import ChatOpenAI
+from src.agent.service import AgentService
+from src.planning.service import PlaningService
+
# @pytest.mark.skip
@pytest.mark.asyncio
@@ -16,9 +13,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.'
timestamp = 'kayak_com_flight_search'
- browser = BrowserService()
+ agent = AgentService()
model = ChatOpenAI(model='gpt-4o')
- planning_service = PlaningService(task, model, browser)
+ planning_service = PlaningService(task, model, agent)
vision = True
@@ -37,49 +34,48 @@ async def test_kayak_flight_search():
print('🚀 Starting flight search task')
print('=' * 50)
- default_actions = actions.get_default_actions()
-
- agent = PlaningAgent(task, str(default_actions), 'gpt-4o')
- agent.update_system_prompt(f'Your task is: {task}')
-
url_history = []
- output = ActionResult()
+ # output = AgentActionResult(done)
max_steps = 50
for i in range(max_steps):
print(f'\n📍 Step {i+1}')
- current_state: PageState = state_manager.get_current_state(run_folder=run_folder, step=i)
- save_formatted_html(
- current_state.interactable_elements, f'{run_folder}/current_state_{i}.html'
- )
- # save normal html
- save_formatted_html(driver.page_source, f'{run_folder}/html_{i}.html')
-
- url_history.append(driver.current_url)
-
- state_text = f'Current interactive elements: {current_state.interactable_elements}'
- if output.extracted_content:
- state_text += f', Extracted content: {output.extracted_content}'
- if output.user_input:
- agent.update_system_prompt(output.user_input)
- state_text += f', User input: {output.user_input}'
- if output.error:
- state_text += f', Previous action error: {output.error}'
-
- input('Press Enter to continue...')
-
- action = await agent.chat(
- state_text,
- images=current_state.screenshot,
- store_conversation=f'{run_folder}/conversation_{i}.txt',
- )
- output: ActionResult = actions.execute_action(action, current_state.selector_map)
-
- # check if output is exactly True (boolean)
- if output.done:
- break
-
- time.sleep(0.5)
+ action, result = await planning_service.step()
+
+ print('action:', action)
+ print('result:', result)
+ # current_state = agent.get_current_state()
+ # save_formatted_html(
+ # current_state.interactable_elements, f'{run_folder}/current_state_{i}.html'
+ # )
+ # # save normal html
+ # save_formatted_html(driver.page_source, f'{run_folder}/html_{i}.html')
+
+ # url_history.append(driver.current_url)
+
+ # state_text = f'Current interactive elements: {current_state.interactable_elements}'
+ # if output.extracted_content:
+ # state_text += f', Extracted content: {output.extracted_content}'
+ # if output.user_input:
+ # agent.update_system_prompt(output.user_input)
+ # state_text += f', User input: {output.user_input}'
+ # if output.error:
+ # state_text += f', Previous action error: {output.error}'
+
+ # input('Press Enter to continue...')
+
+ # action = await agent.chat(
+ # state_text,
+ # images=current_state.screenshot,
+ # store_conversation=f'{run_folder}/conversation_{i}.txt',
+ # )
+ # output: ActionResult = actions.execute_action(action, current_state.selector_map)
+
+ # # check if output is exactly True (boolean)
+ # if output.done:
+ # break
+
+ # time.sleep(0.5)
else:
print('\n' + '=' * 50)