Skip to content

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

Included vision model

magmuellerc1f7bc209e6a
diff --git a/src/agent_interface/planing_agent.py b/src/agent_interface/planing_agent.py
index b623162dc..8be71572e 100644
--- a/src/agent_interface/planing_agent.py
+++ b/src/agent_interface/planing_agent.py
@@ -1,9 +1,11 @@
+import decimal
+
from dotenv import load_dotenv
from tokencost import calculate_all_costs_and_tokens
from src.actions.browser_actions import Action
from src.llm.service import LLM, AvailableModel
-from src.state_manager.utils import save_conversation
+from src.state_manager.utils import encode_image, save_conversation
class PlaningAgent:
@@ -17,20 +19,29 @@ class PlaningAgent:
self.messages_all = []
self.messages = []
- async def chat(
- self, task: str, skip_call: bool = False, store_conversation: str = ''
- ) -> Action:
+ async def chat(self, task: str, store_conversation: str = '', images: str = '') -> Action:
# TODO: include state, actions, etc.
# select next functions to call
- input_messages = self.system_prompt + self.messages + [{'role': 'user', 'content': task}]
-
- if skip_call:
- return Action(action='nothing', goal='', valuation_previous_goal='')
+ if images:
+ # Format message for vision model
+ combined_input = [
+ {'type': 'text', 'text': task},
+ {
+ 'type': 'image_url',
+ 'image_url': {
+ 'url': f'data:image/png;base64,{encode_image(images)}',
+ },
+ },
+ ]
+ else:
+ combined_input = [{'type': 'text', 'text': task}]
+ input_messages = (
+ self.system_prompt + self.messages + [{'role': 'user', 'content': combined_input}]
+ )
response = await self.llm.create_chat_completion(input_messages, Action)
- # self.messages.append({'role': 'user', 'content': '... execute action ...'})
if store_conversation:
# save conversation
save_conversation(input_messages, response.model_dump_json(), store_conversation)
@@ -40,12 +51,32 @@ class PlaningAgent:
try:
# Calculate total cost for all messages
+
+ # check if multiple input
+
+ # can not handly list of content
output = calculate_all_costs_and_tokens(
- input_messages, response.model_dump_json(), self.model
- )
- print(
- f'Total cost: ${output["prompt_cost"] + output["completion_cost"]:,.4f} for {output["prompt_tokens"] + output["completion_tokens"]} tokens'
+ self.system_prompt + self.messages + [{'role': 'user', 'content': task}],
+ response.model_dump_json(),
+ self.model,
)
+ if images:
+ # resolution 1512 x 767
+ image_cost = 0.000213
+ total_cost = (
+ output['prompt_cost']
+ + output['completion_cost']
+ + decimal.Decimal(str(image_cost))
+ )
+ print(
+ f'Text ${output["prompt_cost"]:,.4f} + Image ${image_cost:,.4f} = ${total_cost:,.4f} for {output["prompt_tokens"] + output["completion_tokens"]} tokens'
+ )
+ else:
+ total_cost = output['prompt_cost'] + output['completion_cost']
+ print(
+ f'Total cost: ${total_cost:,.4f} for {output["prompt_tokens"] + output["completion_tokens"]} tokens'
+ )
+
except Exception as e:
print(f'Error calculating prompt cost: {e}')
diff --git a/src/state_manager/state.py b/src/state_manager/state.py
index 29b6c3aeb..45eaed60b 100644
--- a/src/state_manager/state.py
+++ b/src/state_manager/state.py
@@ -27,7 +27,9 @@ class StateManager:
self.dom_service = DomService(driver)
self.ob = Screenshot.Screenshot()
- def get_current_state(self, run_folder: str, full_page_screenshot: bool = False) -> PageState:
+ def get_current_state(
+ self, run_folder: str, full_page_screenshot: bool = False, step: int = 0
+ ) -> PageState:
"""
Retrieves current URL and interactable elements from processed HTML.
@@ -37,16 +39,17 @@ class StateManager:
processed_content = self.dom_service.get_current_state()
if full_page_screenshot:
+ # this takes longer because of scrolling
screenshot = self.ob.full_screenshot(
self.driver,
save_path=run_folder,
- image_name='selenium_full_screenshot.png',
+ image_name=f'selenium_full_screenshot_{step}.png',
is_load_at_runtime=True,
- load_wait_time=0,
+ load_wait_time=1,
)
- screenshot = run_folder + '/selenium_full_screenshot.png'
+ screenshot = run_folder + f'/selenium_full_screenshot_{step}.png'
else:
- file_name = run_folder + '/window_screenshot.png'
+ file_name = run_folder + f'/window_screenshot_{step}.png'
screenshot = self.driver.get_screenshot_as_file(file_name)
screenshot = file_name if screenshot else ''
diff --git a/src/state_manager/utils.py b/src/state_manager/utils.py
index 207b57e84..9f32b3d67 100644
--- a/src/state_manager/utils.py
+++ b/src/state_manager/utils.py
@@ -1,3 +1,4 @@
+import base64
import os
from bs4 import BeautifulSoup
@@ -34,3 +35,9 @@ def save_markdown(markdown_content, output_file_name):
output_path = os.path.join(output_file_name)
with open(output_path, 'w', encoding='utf-8') as f:
f.write(markdown_content)
+
+
+def encode_image(image_path):
+ """Encode image to base64 string"""
+ with open(image_path, 'rb') as image_file:
+ return base64.b64encode(image_file.read()).decode('utf-8')
diff --git a/src/tests/test_kayak_search.py b/src/tests/test_kayak_search.py
index 44f24b4cd..e2cd7ce20 100644
--- a/src/tests/test_kayak_search.py
+++ b/src/tests/test_kayak_search.py
@@ -1,3 +1,4 @@
+import base64
import os
import time
@@ -7,7 +8,7 @@ from src.actions.browser_actions import ActionResult, BrowserActions
from src.agent_interface.planing_agent import PlaningAgent
from src.driver.service import DriverService
from src.state_manager.state import PageState, StateManager
-from src.state_manager.utils import save_formatted_html
+from src.state_manager.utils import encode_image, save_formatted_html
@pytest.fixture
@@ -24,8 +25,6 @@ async def test_kayak_flight_search(setup):
driver, actions, state_manager = setup
# Create run folder
- # timestamp = 'meta'
- # task = 'apply for a job at meta internship for ml research in sunny vale'
timestamp = 'flight_search_bali_to_kirgistan'
task = 'find a flight from Bali to Kirgistan on 2024-11-25 for 2 people one way.'
vision = True
@@ -49,25 +48,13 @@ async def test_kayak_flight_search(setup):
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)
+ 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')
- # show image and pause
- # if vision:
- # import matplotlib.pyplot as plt
-
- # # read path and show image
- # # image = plt.imread(current_state.screenshot)
- # # # no axis
- # # plt.axis('off')
-
- # # plt.imshow(image)
- # plt.pause(5)
-
url_history.append(driver.current_url)
state_text = f'Current interactive elements: {current_state.interactable_elements}'
@@ -80,7 +67,9 @@ async def test_kayak_flight_search(setup):
state_text += f', Previous action error: {output.error}'
action = await agent.chat(
- state_text, skip_call=False, store_conversation=f'{run_folder}/conversation_{i}.txt'
+ state_text,
+ images=current_state.screenshot,
+ store_conversation=f'{run_folder}/conversation_{i}.txt',
)
output: ActionResult = actions.execute_action(action, current_state.selector_map)