Skip to content

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

Calculate complete cost and reorde model output

magmueller5454860ea326
diff --git a/src/actions/browser_actions.py b/src/actions/browser_actions.py
index e15a11dfa..3c5f40c29 100644
--- a/src/actions/browser_actions.py
+++ b/src/actions/browser_actions.py
@@ -21,10 +21,10 @@ class ActionParams(BaseModel):
class Action(BaseModel):
+ valuation_previous_goal: str
+ goal: str
action: str
params: Optional[ActionParams] = None
- goal: str
- valuation_previous_goal: str
@property
def is_valid(self) -> bool:
@@ -37,6 +37,7 @@ class ActionResult(BaseModel):
done: bool = False
extracted_content: str = ''
user_input: str = ''
+ error: Optional[str] = None
class BrowserActions:
@@ -57,53 +58,60 @@ class BrowserActions:
# params = action.params.model_dump() if action.params else {}
output = ActionResult()
- if action_name == 'search_google':
- if action.params and action.params.text:
- self.search_google(action.params.text)
- else:
- raise Exception('Query is required for search_google action')
- elif action_name == 'nothing':
- pass
- elif action_name == 'go_to_url':
- if action.params and action.params.url:
- self.go_to_url(action.params.url)
- else:
- raise Exception('Url is required for go_to_url action')
- elif action_name == 'go_back':
- self.go_back()
- elif action_name == 'done':
- output.done = True
-
- elif action_name == 'text_input':
- if action.params and action.params.id and action.params.text:
- self.input_text_by_index(action.params.id, action.params.text)
- else:
- raise Exception('Id and text are required for input action')
- elif action_name == 'click':
- if action.params and (action.params.id or action.params.id == 0):
- self.click_element_by_index(action.params.id)
- else:
- raise Exception('Id is required for click action')
- elif action_name == 'ask_user':
- if action.params and action.params.text:
- output.user_input = self.ask_user(action.params.text)
- else:
- raise Exception('Question is required for ask_user action')
- elif action_name == 'send_user_text':
- if action.params and action.params.text:
- self.send_user_text(action.params.text)
+ try:
+ if action_name == 'search_google':
+ if action.params and action.params.text:
+ self.search_google(action.params.text)
+ else:
+ raise Exception('Query is required for search_google action')
+ elif action_name == 'nothing':
+ pass
+ elif action_name == 'go_to_url':
+ if action.params and action.params.url:
+ self.go_to_url(action.params.url)
+ else:
+ raise Exception('Url is required for go_to_url action')
+ elif action_name == 'go_back':
+ self.go_back()
+ elif action_name == 'done':
+ output.done = True
+
+ elif action_name == 'text_input':
+ if action.params and action.params.id and action.params.text:
+ self.input_text_by_index(action.params.id, action.params.text)
+ else:
+ raise Exception('Id and text are required for input action')
+ elif action_name == 'click':
+ if action.params and (action.params.id or action.params.id == 0):
+ self.click_element_by_index(action.params.id)
+ else:
+ raise Exception('Id is required for click action')
+ elif action_name == 'ask_user':
+ if action.params and action.params.text:
+ output.user_input = self.ask_user(action.params.text)
+ else:
+ raise Exception('Question is required for ask_user action')
+ elif action_name == 'send_user_text':
+ if action.params and action.params.text:
+ self.send_user_text(action.params.text)
+ else:
+ raise Exception('Text is required for send_user_text action')
+ elif action_name == 'extract_page_content':
+ output.extracted_content = self.extract_page_content()
+ # elif action_name == 'accept_cookies':
+ # self.driver.accept_cookies()
else:
- raise Exception('Text is required for send_user_text action')
- elif action_name == 'extract_page_content':
- output.extracted_content = self.extract_page_content()
- # elif action_name == 'accept_cookies':
- # self.driver.accept_cookies()
- else:
- raise Exception(f'Action {action_name} not found')
+ raise Exception(f'Action {action_name} not found')
+
+ except Exception as e:
+ output.error = str(e)
return output
def done(self):
+ print('\n' + '=' * 50)
+ print('✅ Task completed successfully!')
+ print('=' * 50)
return True
def click_element_by_index(self, index: int):
diff --git a/src/agent_interface/planing_agent.py b/src/agent_interface/planing_agent.py
index 3b7f154d9..b623162dc 100644
--- a/src/agent_interface/planing_agent.py
+++ b/src/agent_interface/planing_agent.py
@@ -1,5 +1,5 @@
from dotenv import load_dotenv
-from tokencost import calculate_prompt_cost, count_string_tokens
+from tokencost import calculate_all_costs_and_tokens
from src.actions.browser_actions import Action
from src.llm.service import LLM, AvailableModel
@@ -25,23 +25,8 @@ class PlaningAgent:
# select next functions to call
input_messages = self.system_prompt + self.messages + [{'role': 'user', 'content': task}]
- try:
- # Calculate total cost for all messages
- total_cost = calculate_prompt_cost(input_messages, self.model)
- total_tokens = count_string_tokens(
- ' '.join([m['content'] for m in input_messages]), self.model
- )
- print(
- 'Total prompt cost: ',
- f'${total_cost:,.2f}',
- 'Total tokens: ',
- f'{total_tokens:,}',
- )
- except Exception as e:
- print(f'Error calculating prompt cost: {e}')
-
if skip_call:
- return Action(action='nothing')
+ return Action(action='nothing', goal='', valuation_previous_goal='')
response = await self.llm.create_chat_completion(input_messages, Action)
@@ -53,6 +38,17 @@ class PlaningAgent:
# Only append the output message
self.messages.append({'role': 'assistant', 'content': response.model_dump_json()})
+ try:
+ # Calculate total cost for all messages
+ 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'
+ )
+ except Exception as e:
+ print(f'Error calculating prompt cost: {e}')
+
# keep newest 20 messages
if len(self.messages) > 20:
self.messages = self.messages[-20:]
diff --git a/src/tests/test_kayak_search.py b/src/tests/test_kayak_search.py
index 0869014db..8c2d78d8f 100644
--- a/src/tests/test_kayak_search.py
+++ b/src/tests/test_kayak_search.py
@@ -24,8 +24,12 @@ async def test_kayak_flight_search(setup):
driver, actions, state_manager = setup
# Create run folder
- timestamp = 'bali_flight_search'
- run_folder = f'temp/run_{timestamp}'
+ # 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.'
+
+ run_folder = f'temp/{timestamp}'
if not os.path.exists(run_folder):
os.makedirs(run_folder)
@@ -33,15 +37,14 @@ async def test_kayak_flight_search(setup):
print('🚀 Starting flight search task')
print('=' * 50)
- task = ' find a flight from Zürich to (ask the user for the destination) on 2024-11-25 with return on 2024-12-09 for 2 people.'
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 = []
- extracted_content = ''
- user_input = ''
+ output = ActionResult()
+
max_steps = 50
for i in range(max_steps):
print(f'\n📍 Step {i+1}')
@@ -54,11 +57,13 @@ async def test_kayak_flight_search(setup):
url_history.append(driver.current_url)
state_text = f'Current interactive elements: {current_state.interactable_elements}'
- # , Url history: {url_history}
- if extracted_content:
- state_text += f', Extracted content: {extracted_content}'
- if user_input:
- state_text += f', User input: {user_input}'
+ 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}'
action = await agent.chat(
state_text, skip_call=False, store_conversation=f'{run_folder}/conversation_{i}.txt'
@@ -67,21 +72,12 @@ async def test_kayak_flight_search(setup):
# check if output is exactly True (boolean)
if output.done:
- print('\n' + '=' * 50)
- print('✅ Task completed successfully!')
- print('=' * 50)
break
- if output.extracted_content:
- extracted_content = output.extracted_content
- if output.user_input:
- # update system prompt
- agent.update_system_prompt(output.user_input)
- user_input = output.user_input
time.sleep(0.5)
else:
print('\n' + '=' * 50)
print('❌ Failed to complete task in maximum steps')
print('=' * 50)
- assert False, 'Failed to complete flight search task in maximum steps'
+ assert False, 'Failed to complete task in maximum steps'