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
Squashed commit langchain to native
Gregor Žunič7a10ae0c968b
diff --git a/.cursor/rules/browser-use-rules.mdc b/.cursor/rules/browser-use-rules.mdcindex 899cfbb7d..c58b40ef3 100644--- a/.cursor/rules/browser-use-rules.mdc+++ b/.cursor/rules/browser-use-rules.mdc@@ -73,7 +73,7 @@ To define a task and run a browser-use agent:```pythonfrom browser_use import Agent-from langchain.chat_models import ChatOpenAI+from browser_use.llm import ChatOpenAItask = "Find the CEO of OpenAI and return their name"model = ChatOpenAI(model="gpt-4o")@@ -82,3 +82,7 @@ agent = Agent(task=task, llm=model, controller=controller)history = await agent.run()```++# Never create random examples++When I ask you to implement a feature never create new files that show off that feature -> the code just gets messy. If you do anything to test it out, just do the inline code inside the terminal (if you want).diff --git a/.env.example b/.env.exampleindex f239b8108..b450a0e1a 100644--- a/.env.example+++ b/.env.example@@ -13,5 +13,8 @@ ANONYMIZED_TELEMETRY=true# LogLevel: Set to debug to enable verbose logging, set to result to get results only. Available: result | debug | infoBROWSER_USE_LOGGING_LEVEL=info+# Calculate costs: (beta) Add cost calculations to tokens. Available: true | false+BROWSER_USE_CALCULATE_COST=false+# set this to true to optimize browser-use's chrome for running inside dockerIN_DOCKER=falsediff --git a/.github/ISSUE_TEMPLATE/1_element_detection_bug.yml b/.github/ISSUE_TEMPLATE/1_element_detection_bug.ymlindex c82676e4c..cd38ab813 100644--- a/.github/ISSUE_TEMPLATE/1_element_detection_bug.yml+++ b/.github/ISSUE_TEMPLATE/1_element_detection_bug.yml@@ -20,7 +20,6 @@ body:> - 🆕 [`beta`](https://docs.browser-use.com/development/local-setup): `uv pip install --upgrade git+https://github.com/browser-use/browser-use.git@main`> - 📦 [`stable`](https://pypi.org/project/browser-use/#history): `uv pip install --upgrade browser-use`-- type: inputid: versionattributes:@@ -111,7 +110,7 @@ body:from dotenv import load_dotenvload_dotenv() # tip: always load_dotenv() before other importsfrom browser_use import Agent, BrowserSession, Controller- from langchain_openai import ChatOpenAI+ from browser_use.llm import ChatOpenAIagent = Agent(task='...',diff --git a/.github/ISSUE_TEMPLATE/2_bug_report.yml b/.github/ISSUE_TEMPLATE/2_bug_report.ymlindex a9b228507..39bbc9b2c 100644--- a/.github/ISSUE_TEMPLATE/2_bug_report.yml+++ b/.github/ISSUE_TEMPLATE/2_bug_report.yml@@ -54,7 +54,7 @@ body:from dotenv import load_dotenvload_dotenv() # tip: always load_dotenv() before other importsfrom browser_use import Agent, BrowserSession, Controller- from langchain_openai import ChatOpenAI+ from browser_use.llm import ChatOpenAIagent = Agent(task='...',diff --git a/README.md b/README.mdindex 4bc6ac8c4..d854f7df2 100644--- a/README.md+++ b/README.md@@ -28,13 +28,14 @@ With pip (Python>=3.11):pip install browser-use```-For memory functionality (requires Python<3.13 due to PyTorch compatibility):+For memory functionality (requires Python<3.13 due to PyTorch compatibility):```bashpip install "browser-use[memory]"```Install the browser:+```bashplaywright install chromium --with-deps --no-shell```@@ -46,7 +47,7 @@ import asynciofrom dotenv import load_dotenvload_dotenv()from browser_use import Agent-from langchain_openai import ChatOpenAI+from browser_use.llm import ChatOpenAIasync def main():agent = Agent(@@ -156,12 +157,10 @@ Tell your computer what to do, and it gets it done.- [ ] Human work is sequential. The real power of a browser agent comes into reality if we can parallelize similar tasks. For example, if you want to find contact information for 100 companies, this can all be done in parallel and reported back to a main agent, which processes the results and kicks off parallel subtasks again.-## ContributingWe love contributions! Feel free to open issues for bugs or feature requests. To contribute to the docs, check out the `/docs` folder.-## 🧪 How to make your agents robust?We offer to run your tasks in our CI—automatically, on every update!@@ -173,7 +172,6 @@ We offer to run your tasks in our CI—automatically, on every update!To learn more about the library, check out the [local setup 📕](https://docs.browser-use.com/development/local-setup).-`main` is the primary development branch with frequent changes. For production use, install a stable [versioned release](https://github.com/browser-use/browser-use/releases) instead.---diff --git a/browser_use/agent/cloud_events.py b/browser_use/agent/cloud_events.pyindex 5b1092fa9..ce1d63bd1 100644--- a/browser_use/agent/cloud_events.py+++ b/browser_use/agent/cloud_events.py@@ -188,7 +188,7 @@ class CreateAgentTaskEvent(BaseEvent):user_id='', # To be filled by cloud handleragent_session_id=str(agent.session_id),task=agent.task,- llm_model=agent.model_name,+ llm_model=agent.llm.model_name,agent_state=agent.state.model_dump() if hasattr(agent.state, 'model_dump') else {},stopped=False,paused=False,diff --git a/browser_use/agent/gif.py b/browser_use/agent/gif.pyindex e08e17924..99cc6ea19 100644--- a/browser_use/agent/gif.py+++ b/browser_use/agent/gif.py@@ -199,7 +199,7 @@ def _create_task_frame(else:font_size = base_font_size- larger_font = ImageFont.truetype(regular_font.path, font_size)+ larger_font = ImageFont.truetype(regular_font.path, font_size) # type: ignore# Generate wrapped text with the calculated font sizewrapped_text = _wrap_text(task, larger_font, max_width)diff --git a/browser_use/agent/memory/service.py b/browser_use/agent/memory/service.pyindex a57fdc4de..379dda277 100644--- a/browser_use/agent/memory/service.py+++ b/browser_use/agent/memory/service.py@@ -5,17 +5,14 @@ import osimport warningsfrom concurrent.futures import ThreadPoolExecutor, TimeoutError-from langchain_core.language_models.chat_models import BaseChatModel-from langchain_core.messages import (- BaseMessage,- HumanMessage,-)-from langchain_core.messages.utils import convert_to_openai_messages-from browser_use.agent.memory.views import MemoryConfigfrom browser_use.agent.message_manager.service import MessageManagerfrom browser_use.agent.message_manager.views import ManagedMessage, MessageMetadatafrom browser_use.config import CONFIG+from browser_use.llm import UserMessage+from browser_use.llm.base import BaseChatModel+from browser_use.llm.messages import BaseMessage+from browser_use.llm.openai.serializer import OpenAIMessageSerializerfrom browser_use.utils import time_execution_sync@@ -102,7 +99,7 @@ class Memory:# Add the history_db_path to the configconfig_with_history_path = self.config.full_config_dict.copy()- config_with_history_path['history_db_path'] = history_db_path+ config_with_history_path['history_db_path'] = history_db_path # type: ignore# Try again with the new configself.mem0 = Mem0Memory.from_config(config_dict=config_with_history_path)@@ -132,7 +129,7 @@ class Memory:# Keep system and memory messages as they arenew_messages.append(msg)else:- if len(msg.message.content) > 0:+ if len(msg.message.text) > 0:messages_to_process.append(msg)# Need at least 2 messages to create a meaningful summary@@ -156,24 +153,19 @@ class Memory:return# Replace the processed messages with the consolidated memory- memory_message = HumanMessage(content=memory_content)- memory_tokens = self.message_manager._count_tokens(memory_message)- memory_metadata = MessageMetadata(tokens=memory_tokens, message_type='memory')-- # Calculate the total tokens being removed- removed_tokens = sum(m.metadata.tokens for m in messages_to_process)+ memory_message = UserMessage(content=memory_content)+ memory_metadata = MessageMetadata(message_type='memory')# Add the memory messagenew_messages.append(ManagedMessage(message=memory_message, metadata=memory_metadata))# Update the historyself.message_manager.state.history.messages = new_messages- self.message_manager.state.history.current_tokens -= removed_tokens- self.message_manager.state.history.current_tokens += memory_tokens+self.logger.info(f'📜 History consolidated: {len(messages_to_process)} steps converted to long-term memory')def _create(self, messages: list[BaseMessage], current_step: int) -> str | None:- parsed_messages = convert_to_openai_messages(messages)+ parsed_messages = OpenAIMessageSerializer.serialize_messages(messages)try:results = self.mem0.add(messages=parsed_messages,diff --git a/browser_use/agent/memory/views.py b/browser_use/agent/memory/views.pyindex 2a52adc0c..e06d319fc 100644--- a/browser_use/agent/memory/views.py+++ b/browser_use/agent/memory/views.py@@ -1,8 +1,9 @@from typing import Any, Literal-from langchain_core.language_models.chat_models import BaseChatModelfrom pydantic import BaseModel, ConfigDict, Field+from browser_use.llm.base import BaseChatModel+class MemoryConfig(BaseModel):"""Configuration for procedural memory."""@@ -84,7 +85,7 @@ class MemoryConfig(BaseModel):# --- Default collection_name handling ---if self.vector_store_collection_name:- provider_specific_config['collection_name'] = self.vector_store_collection_name+ provider_specific_config['collection_name'] = self.vector_store_collection_name # type: ignoreelse:is_local_file_storage_mode = Falseis_qdrant_server_mode = False@@ -112,27 +113,27 @@ class MemoryConfig(BaseModel):is_qdrant_server_mode = Trueif is_local_file_storage_mode:- provider_specific_config['collection_name'] = f'mem0_{self.vector_store_provider}_{self.embedder_dims}'+ provider_specific_config['collection_name'] = f'mem0_{self.vector_store_provider}_{self.embedder_dims}' # type: ignoreelif self.vector_store_provider == 'upstash_vector':- provider_specific_config['collection_name'] = ''+ provider_specific_config['collection_name'] = '' # type: ignoreelif (self.vector_store_providerin ['elasticsearch', 'milvus', 'pgvector', 'redis', 'weaviate', 'supabase', 'azure_ai_search']or (self.vector_store_provider == 'qdrant' and is_qdrant_server_mode and not is_local_file_storage_mode)or (self.vector_store_provider == 'qdrant' and not is_local_file_storage_mode)): # Qdrant in explicit server mode- provider_specific_config['collection_name'] = 'mem0'+ provider_specific_config['collection_name'] = 'mem0' # type: ignoreelse:# Fallback for providers like Pinecone, VertexAI (where name is usually user-required)# or if a new provider is added and not yet handled explicitly.- provider_specific_config['collection_name'] = 'mem0_default_collection'+ provider_specific_config['collection_name'] = 'mem0_default_collection' # type: ignore# --- Default path handling for local file-based stores ---default_local_path = f'{self.vector_store_base_path}_{self.embedder_dims}_{self.vector_store_provider}'if self.vector_store_provider == 'faiss':if not (self.vector_store_config_override and 'path' in self.vector_store_config_override):- provider_specific_config['path'] = default_local_path+ provider_specific_config['path'] = default_local_path # type: ignoreelif self.vector_store_provider == 'chroma':# Set default path if Chroma is in local mode and path is not overridden@@ -142,7 +143,7 @@ class MemoryConfig(BaseModel):path_in_override = self.vector_store_config_override and 'path' in self.vector_store_config_overrideif not is_chroma_server_mode and not path_in_override:- provider_specific_config['path'] = default_local_path+ provider_specific_config['path'] = default_local_path # type: ignoreelif self.vector_store_provider == 'qdrant':# Set default path if Qdrant is in local file mode and path is not overridden@@ -155,7 +156,7 @@ class MemoryConfig(BaseModel):)if not has_path_override and not is_server_configured:- provider_specific_config['path'] = default_local_path+ provider_specific_config['path'] = default_local_path # type: ignore# Merge user-provided overrides. These can add new keys or overwrite defaults set above.if self.vector_store_config_override:diff --git a/browser_use/agent/message_manager/service.py b/browser_use/agent/message_manager/service.pyindex d52e0b45a..b7b75d8ae 100644--- a/browser_use/agent/message_manager/service.py+++ b/browser_use/agent/message_manager/service.py@@ -1,23 +1,30 @@from __future__ import annotations+import jsonimport logging-import re-import shutil-from langchain_core.messages import (- AIMessage,- BaseMessage,- HumanMessage,- SystemMessage,- ToolMessage,-)from pydantic import BaseModel-from browser_use.agent.message_manager.views import ManagedMessage, MessageMetadata+from browser_use.agent.message_manager.views import (+ MessageMetadata,+ SupportedMessageTypes,+)from browser_use.agent.prompts import AgentMessagePrompt-from browser_use.agent.views import ActionResult, AgentOutput, AgentStepInfo, MessageManagerState+from browser_use.agent.views import (+ ActionResult,+ AgentOutput,+ AgentStepInfo,+ MessageManagerState,+)from browser_use.browser.views import BrowserStateSummaryfrom browser_use.filesystem.file_system import FileSystem+from browser_use.llm.messages import (+ AssistantMessage,+ BaseMessage,+ ContentPartTextParam,+ SystemMessage,+ UserMessage,+)from browser_use.utils import match_url_with_domain_pattern, time_execution_synclogger = logging.getLogger(__name__)@@ -29,124 +36,26 @@ logger = logging.getLogger(__name__)# All logging functions start with _log_ for easy identification.-def _log_get_message_emoji(message_type: str) -> str:+def _log_get_message_emoji(message: BaseMessage) -> str:"""Get emoji for a message type - used only for logging display"""emoji_map = {- 'HumanMessage': '💬',- 'AIMessage': '🧠',- 'ToolMessage': '🔨',+ 'UserMessage': '💬',+ 'SystemMessage': '🧠',+ 'AssistantMessage': '🔨',}- return emoji_map.get(message_type, '🎮')+ return emoji_map.get(message.__class__.__name__, '🎮')-def _log_clean_whitespace(text: str) -> str:- """Replace all repeated whitespace with single space and strip - used only for logging display"""- return re.sub(r'\s+', ' ', text).strip()---def _log_extract_text_from_list_content(content: list) -> str:- """Extract text from list content structure - used only for logging display"""- text_content = ''- for item in content:- if isinstance(item, dict) and 'text' in item:- text_content += item['text']- return text_content---def _log_format_agent_output_content(tool_call: dict) -> str:- """Format AgentOutput tool call into readable content - used only for logging display"""- try:- args = tool_call.get('args', {})- action_info = ''-- # Get action name- if 'action' in args and args['action']:- first_action = args['action'][0] if isinstance(args['action'], list) and args['action'] else args['action']- if isinstance(first_action, dict):- action_name = next(iter(first_action.keys())) if first_action else 'unknown'- action_info = f'{action_name}()'-- # Get goal- goal_info = ''- if 'current_state' in args and isinstance(args['current_state'], dict):- next_goal = args['current_state'].get('next_goal', '').strip()- if next_goal:- # Clean whitespace from goal text to prevent newlines- next_goal = _log_clean_whitespace(next_goal)- goal_info = f': {next_goal}'-- # Combine action and goal info- if action_info and goal_info:- return f'{action_info}{goal_info}'- elif action_info:- return action_info- elif goal_info:- return goal_info[2:] # Remove ': ' prefix for goal-only- else:- return 'AgentOutput'- except Exception as e:- logger.warning(f'Failed to format agent output content for logging: {e}')- return 'AgentOutput'---def _log_extract_message_content(message: BaseMessage, is_last_message: bool, metadata: MessageMetadata | None = None) -> str:- """Extract content from a message for logging display only"""- try:- message_type = message.__class__.__name__-- if is_last_message and message_type == 'HumanMessage' and isinstance(message.content, list):- # Special handling for last message with list content- text_content = _log_extract_text_from_list_content(message.content)- text_content = _log_clean_whitespace(text_content)-- # Look for current state section- if '[Current state starts here]' in text_content:- start_idx = text_content.find('[Current state starts here]')- return text_content[start_idx:]- return text_content-- # Standard content extraction- cleaned_content = _log_clean_whitespace(str(message.content))-- # Handle AIMessages with tool calls- if isinstance(message, AIMessage) and hasattr(message, 'tool_calls') and message.tool_calls and not cleaned_content:- tool_call = message.tool_calls[0]- tool_name = tool_call.get('name', 'unknown')-- if tool_name == 'AgentOutput':- # Skip formatting for init example messages- if metadata and metadata.message_type == 'init':- return '[Example AgentOutput]'- content = _log_format_agent_output_content(dict(tool_call)) # Convert ToolCall to dict- else:- content = f'[TOOL: {tool_name}]'- else:- content = cleaned_content-- # Shorten "Action result:" to "Result:" for display- if content.startswith('Action result:'):- content = 'Result:' + content[14:]-- return content- except Exception as e:- logger.warning(f'Failed to extract message content for logging: {e}')- return '[Error extracting content]'---def _log_format_message_line(- message_with_metadata: object, content: str, is_last_message: bool, terminal_width: int-) -> list[str]:+def _log_format_message_line(message: BaseMessage, content: str, is_last_message: bool, terminal_width: int) -> list[str]:"""Format a single message for logging display"""try:lines = []# Get emoji and token info- if isinstance(message_with_metadata, ManagedMessage):- message_type = message_with_metadata.message.__class__.__name__- emoji = _log_get_message_emoji(message_type)- token_str = str(message_with_metadata.metadata.tokens).rjust(4)- else:- return ['❓[ ?]: [Invalid message format]']+ emoji = _log_get_message_emoji(message)+ # token_str = str(message.metadata.tokens).rjust(4)+ # TODO: fix the token count+ token_str = '??? (TODO)'prefix = f'{emoji}[{token_str}]: '# Calculate available width (emoji=2 visual cols + [token]: =8 chars)@@ -188,9 +97,6 @@ def _log_format_message_line(class MessageManagerSettings(BaseModel):- max_input_tokens: int = 128000- estimated_characters_per_token: int = 3- image_tokens: int = 800include_attributes: list[str] = []message_context: str | None = None# Support both old format {key: value} and new format {domain: {key: value}}@@ -223,45 +129,32 @@ class MessageManager:def _init_messages(self) -> None:"""Initialize the message history with system message, context, task, and other initial messages"""- self._add_message_with_tokens(self.system_prompt, message_type='init')+ self._add_message_with_type(self.system_prompt, message_type='init')- if self.settings.message_context:- context_message = HumanMessage(content='<task_context>' + self.settings.message_context + '</task_context>')- self._add_message_with_tokens(context_message, message_type='init')-- if self.settings.sensitive_data:- info = f'<sensitive_data>Here are placeholders for sensitive data: {list(self.settings.sensitive_data.keys())}'- info += '\nTo use them, write <secret>the placeholder name</secret> </sensitive_data>'- info_message = HumanMessage(content=info)- self._add_message_with_tokens(info_message, message_type='init')-- placeholder_message = HumanMessage(+ placeholder_message = UserMessage(content='<example_1>\nHere is an example output of thinking and tool call. You can use it as a reference but do not copy it exactly.')# placeholder_message = HumanMessage(content='Example output:')- self._add_message_with_tokens(placeholder_message, message_type='init')+ self._add_message_with_type(placeholder_message, message_type='init')- example_tool_call_1 = AIMessage(- content='',- tool_calls=[+ example_tool_call_1 = AssistantMessage(+ content=json.dumps({- 'name': 'AgentOutput',- 'args': {- 'thinking': """I have successfully navigated to https://github.com/explore and can see the page has loaded with a list of featured repositories. The page contains interactive elements and I can identify specific repositories like bytedance/UI-TARS-desktop (index [4]) and ray-project/kuberay (index [5]). The user's request is to explore GitHub repositories and collect information about them such as descriptions, stars, or other metadata. So far, I haven't collected any information.+ 'thinking': """I have successfully navigated to https://github.com/explore and can see the page has loaded with a list of featured repositories. The page contains interactive elements and I can identify specific repositories like bytedance/UI-TARS-desktop (index [4]) and ray-project/kuberay (index [5]). The user's request is to explore GitHub repositories and collect information about them such as descriptions, stars, or other metadata. So far, I haven't collected any information.My navigation to the GitHub explore page was successful. The page loaded correctly and I can see the expected content.I need to capture the key repositories I've identified so far into my memory and into a file.Since this appears to be a multi-step task involving visiting multiple repositories and collecting their information, I need to create a structured plan in todo.md.After writing todo.md, I can also initialize a github.md file to accumulate the information I've collected.The file system actions do not change the browser state, so I can also click on the bytedance/UI-TARS-desktop (index [4]) to start collecting information.""",- 'evaluation_previous_goal': 'Navigated to GitHub explore page. Verdict: Success',- 'memory': 'Found initial repositories such as bytedance/UI-TARS-desktop and ray-project/kuberay.',- 'next_goal': 'Create todo.md checklist to track progress, initialize github.md for collecting information, and click on bytedance/UI-TARS-desktop.',- 'action': [- {- 'write_file': {- 'path': 'todo.md',- 'content': """+ 'evaluation_previous_goal': 'Navigated to GitHub explore page. Verdict: Success',+ 'memory': 'Found initial repositories such as bytedance/UI-TARS-desktop and ray-project/kuberay.',+ 'next_goal': 'Create todo.md checklist to track progress, initialize github.md for collecting information, and click on bytedance/UI-TARS-desktop.',+ 'action': [+ {+ 'write_file': {+ 'path': 'todo.md',+ 'content': """# Interesting Github Repositories in Explore Section## Tasks@@ -274,74 +167,73 @@ The file system actions do not change the browser state, so I can also click on- [ ] Validate that I have not missed anything in the page- [ ] Report final results to user""".strip('\n'),- }- },- {- 'write_file': {- 'path': 'github.md',- 'content': """+ }+ },+ {+ 'write_file': {+ 'path': 'github.md',+ 'content': """# Github Repositories:""",- }- },- {- 'click_element_by_index': {- 'index': 4,- }- },- ],- },- 'id': str(self.state.tool_id),- 'type': 'tool_call',- },- ],+ }+ },+ {+ 'click_element_by_index': {+ 'index': 4,+ }+ },+ ],+ }+ ))- self._add_message_with_tokens(example_tool_call_1, message_type='init')- self.add_tool_message(- content='Data written to todo.md.\nData written to github.md.\nClicked element with index 4.\n</example_1>',+ self._add_message_with_type(example_tool_call_1, message_type='init')+ self._add_message_with_type(+ UserMessage(+ content='Data written to todo.md.\nData written to github.md.\nClicked element with index 4.\n</example_1>',+ ),message_type='init',)- placeholder_message = HumanMessage(content='<example_2>Example thinking and tool call 2:')+ placeholder_message = UserMessage(content='<example_2>Example thinking and tool call 2:')# self._add_message_with_tokens(placeholder_message, message_type='init')- example_tool_call_2 = AIMessage(- content='',- tool_calls=[- {- 'name': 'AgentOutput',- 'args': {- 'current_state': {- 'thinking': """-**Understanding the Current State:**-I am currently on Apple's main homepage, having successfully clicked on an 'Apple' link in the previous step. The page has loaded and I can see the typical Apple website layout with navigation elements. I can see an interactive element at index [4] that is labeled 'iPhone', which indicates this is a navigation link to Apple's iPhone product section.--**Evaluating the Previous Action:**-The click on the 'Apple' link was successful and brought me to Apple's homepage as expected. The page loaded properly and I can see the navigation structure including the iPhone link. This confirms that the previous navigation action worked correctly and I'm now in the right place to continue with the iPhone-related task.--**Tracking and Planning with todo.md:**-Based on the context, this seems to be part of a larger task involving Apple products. I should be prepared to update my todo.md file if there are multiple iPhone models or other Apple products to investigate. The current goal is to access the iPhone section to see what product information is available.--**Writing Intermediate Results:**-Once I reach the iPhone page, I'll need to extract information about different iPhone models, their specifications, prices, or other details. I should accumulate all findings in results.md in a structured format as I collect the information.--**Preparing what goes into my memory:**-I need to capture that I'm in the process of navigating to the iPhone section and preparing to collect product information.--**Planning my next action:**-My next action is to click on the iPhone link at index [4] to navigate to Apple's iPhone product page. This will give me access to the iPhone lineup and allow me to gather the requested information.-""",- 'evaluation_previous_goal': 'Clicked Apple link and reached the homepage. Verdict: Success',- 'memory': 'On Apple homepage with iPhone link at index [4].',- 'next_goal': 'Click iPhone link.',- },- 'action': [{'click_element_by_index': {'index': 4}}],- },- 'id': str(self.state.tool_id),- 'type': 'tool_call',- },- ],- )+ # TODO: add this back+ # example_tool_call_2 = AssistantMessage(+ # content=json.dumps(+ # {+ # 'name': 'AgentOutput',+ # 'args': {+ # 'current_state': {+ # 'thinking': """I+ # **Understanding the Current State:**+ # I am currently on Apple's main homepage, having successfully clicked on an 'Apple' link in the previous step. The page has loaded and I can see the typical Apple website layout with navigation elements. I can see an interactive element at index [4] that is labeled 'iPhone', which indicates this is a navigation link to Apple's iPhone product section.++ # **Evaluating the Previous Action:**+ # The click on the 'Apple' link was successful and brought me to Apple's homepage as expected. The page loaded properly and I can see the navigation structure including the iPhone link. This confirms that the previous navigation action worked correctly and I'm now in the right place to continue with the iPhone-related task.++ # **Tracking and Planning with todo.md:**+ # Based on the context, this seems to be part of a larger task involving Apple products. I should be prepared to update my todo.md file if there are multiple iPhone models or other Apple products to investigate. The current goal is to access the iPhone section to see what product information is available.++ # **Writing Intermediate Results:**+ # Once I reach the iPhone page, I'll need to extract information about different iPhone models, their specifications, prices, or other details. I should accumulate all findings in results.md in a structured format as I collect the information.++ # **Preparing what goes into my memory:**+ # I need to capture that I'm in the process of navigating to the iPhone section and preparing to collect product information.++ # **Planning my next action:**+ # My next action is to click on the iPhone link at index [4] to navigate to Apple's iPhone product page. This will give me access to the iPhone lineup and allow me to gather the requested information.+ # """,+ # 'evaluation_previous_goal': 'Clicked Apple link and reached the homepage. Verdict: Success',+ # 'memory': 'On Apple homepage with iPhone link at index [4].',+ # 'next_goal': 'Click iPhone link.',+ # },+ # 'action': [{'click_element_by_index': {'index': 4}}],+ # },+ # 'id': str(self.state.tool_id),+ # 'type': 'tool_call',+ # },+ # ),+ # )# self._add_message_with_tokens(example_tool_call_2, message_type='init')# self.add_tool_message(content='Clicked on index [4]. </example_2>', message_type='init')@@ -454,78 +346,67 @@ Next Goal: {model_output.current_state.next_goal}sensitive_data=self.sensitive_data_description,available_file_paths=self.available_file_paths,).get_user_message(use_vision)- self._add_message_with_tokens(state_message)-- def add_model_output(self, model_output: AgentOutput) -> None:- """Add model output as AI message"""- tool_calls = [- {- 'name': 'AgentOutput',- 'args': model_output.model_dump(mode='json', exclude_unset=True),- 'id': str(self.state.tool_id),- 'type': 'tool_call',- }- ]-- msg = AIMessage(- content='',- tool_calls=tool_calls,- )- self._add_message_with_tokens(msg)- # empty tool response- self.add_tool_message(content='')+ self._add_message_with_type(state_message)def add_plan(self, plan: str | None, position: int | None = None) -> None:- if plan:- msg = AIMessage(content=plan)- self._add_message_with_tokens(msg, position)+ if not plan:+ return++ msg = AssistantMessage(content=plan)+ self._add_message_with_type(msg, position)def _log_history_lines(self) -> str:"""Generate a formatted log string of message history for debugging / printing to terminal"""- try:- total_input_tokens = 0- message_lines = []- terminal_width = shutil.get_terminal_size((80, 20)).columns-- for i, m in enumerate(self.state.history.messages):- try:- total_input_tokens += m.metadata.tokens- is_last_message = i == len(self.state.history.messages) - 1-- # Extract content for logging- content = _log_extract_message_content(m.message, is_last_message, m.metadata)-- # Format the message line(s)- lines = _log_format_message_line(m, content, is_last_message, terminal_width)- message_lines.extend(lines)- except Exception as e:- logger.warning(f'Failed to format message {i} for logging: {e}')- # Add a fallback line for this message- message_lines.append('❓[ ?]: [Error formatting this message]')-- # Build final log message- return (- f'📜 LLM Message history ({len(self.state.history.messages)} messages, {total_input_tokens} tokens):\n'- + '\n'.join(message_lines)- )- except Exception as e:- logger.warning(f'Failed to generate history log: {e}')- # Return a minimal fallback message- return f'📜 LLM Message history (error generating log: {e})'+ # TODO: fix logging++ # try:+ # total_input_tokens = 0+ # message_lines = []+ # terminal_width = shutil.get_terminal_size((80, 20)).columns++ # for i, m in enumerate(self.state.history.messages):+ # try:+ # total_input_tokens += m.metadata.tokens+ # is_last_message = i == len(self.state.history.messages) - 1++ # # Extract content for logging+ # content = _log_extract_message_content(m.message, is_last_message, m.metadata)++ # # Format the message line(s)+ # lines = _log_format_message_line(m, content, is_last_message, terminal_width)+ # message_lines.extend(lines)+ # except Exception as e:+ # logger.warning(f'Failed to format message {i} for logging: {e}')+ # # Add a fallback line for this message+ # message_lines.append('❓[ ?]: [Error formatting this message]')++ # # Build final log message+ # return (+ # f'📜 LLM Message history ({len(self.state.history.messages)} messages, {total_input_tokens} tokens):\n'+ # + '\n'.join(message_lines)+ # )+ # except Exception as e:+ # logger.warning(f'Failed to generate history log: {e}')+ # # Return a minimal fallback message+ # return f'📜 LLM Message history (error generating log: {e})'++ return ''@time_execution_sync('--get_messages')def get_messages(self) -> list[BaseMessage]:"""Get current message list, potentially trimmed to max tokens"""- msg = [m.message for m in self.state.history.messages]# Log message history for debugginglogger.debug(self._log_history_lines())- return msg+ return [m.message for m in self.state.history.messages]- def _add_message_with_tokens(- self, message: BaseMessage, position: int | None = None, message_type: str | None = None+ def _add_message_with_type(+ self,+ message: BaseMessage,+ position: int | None = None,+ message_type: SupportedMessageTypes | None = None,) -> None:"""Add message with token count metadataposition: None for last, -1 for second last, etc.@@ -535,8 +416,7 @@ Next Goal: {model_output.current_state.next_goal}if self.settings.sensitive_data:message = self._filter_sensitive_data(message)- token_count = self._count_tokens(message)- metadata = MessageMetadata(tokens=token_count, message_type=message_type)+ metadata = MessageMetadata(message_type=message_type)self.state.history.add_message(message, metadata, position)@time_execution_sync('--filter_sensitive_data')@@ -576,95 +456,11 @@ Next Goal: {model_output.current_state.next_goal}message.content = replace_sensitive(message.content)elif isinstance(message.content, list):for i, item in enumerate(message.content):- if isinstance(item, dict) and 'text' in item:- item['text'] = replace_sensitive(item['text'])+ if isinstance(item, ContentPartTextParam):+ item.text = replace_sensitive(item.text)message.content[i] = itemreturn message- def _count_tokens(self, message: BaseMessage) -> int:- """Count tokens in a message using the model's tokenizer"""- tokens = 0- if isinstance(message.content, list):- for item in message.content:- if 'image_url' in item:- tokens += self.settings.image_tokens- elif isinstance(item, dict) and 'text' in item:- tokens += self._count_text_tokens(item['text'])- else:- msg = message.content- if hasattr(message, 'tool_calls'):- msg += str(message.tool_calls) # type: ignore- tokens += self._count_text_tokens(msg)- return tokens-- def _count_text_tokens(self, text: str) -> int:- """Count tokens in a text string"""- tokens = len(text) // self.settings.estimated_characters_per_token # Rough estimate if no tokenizer available- return tokens-- def cut_messages(self):- """Get current message list, potentially trimmed to max tokens"""- diff = self.state.history.current_tokens - self.settings.max_input_tokens- if diff <= 0:- return None-- msg = self.state.history.messages[-1]-- # if list with image remove image- if isinstance(msg.message.content, list):- text = ''- for item in msg.message.content:- if 'image_url' in item:- msg.message.content.remove(item)- diff -= self.settings.image_tokens- msg.metadata.tokens -= self.settings.image_tokens- self.state.history.current_tokens -= self.settings.image_tokens- logger.debug(- f'Removed image with {self.settings.image_tokens} tokens - total tokens now: {self.state.history.current_tokens}/{self.settings.max_input_tokens}'- )- elif 'text' in item and isinstance(item, dict):- text += item['text']- msg.message.content = text- self.state.history.messages[-1] = msg-- if diff <= 0:- return None-- # if still over, remove text from state message proportionally to the number of tokens needed with buffer- # Calculate the proportion of content to remove- proportion_to_remove = diff / msg.metadata.tokens- if proportion_to_remove > 0.99:- raise ValueError(- f'Max token limit reached - history is too long - reduce the system prompt or task. '- f'proportion_to_remove: {proportion_to_remove}'- )- logger.debug(- f'Removing {proportion_to_remove * 100:.2f}% of the last message {proportion_to_remove * msg.metadata.tokens:.2f} / {msg.metadata.tokens:.2f} tokens)'- )-- content = msg.message.content- characters_to_remove = int(len(content) * proportion_to_remove)- content = content[:-characters_to_remove]-- # remove tokens and old long message- self.state.history.remove_last_state_message()-- # new message with updated content- msg = HumanMessage(content=content)- self._add_message_with_tokens(msg)-- last_msg = self.state.history.messages[-1]-- logger.debug(- f'Added message with {last_msg.metadata.tokens} tokens - total tokens now: {self.state.history.current_tokens}/{self.settings.max_input_tokens} - total messages: {len(self.state.history.messages)}'- )-def _remove_last_state_message(self) -> None:"""Remove last state message from history"""self.state.history.remove_last_state_message()-- def add_tool_message(self, content: str, message_type: str | None = None) -> None:- """Add tool message to history"""- msg = ToolMessage(content=content, tool_call_id=str(self.state.tool_id))- self.state.tool_id += 1- self._add_message_with_tokens(msg, message_type=message_type)diff --git a/browser_use/agent/message_manager/utils.py b/browser_use/agent/message_manager/utils.pyindex beae1856c..f83eba735 100644--- a/browser_use/agent/message_manager/utils.py+++ b/browser_use/agent/message_manager/utils.py@@ -2,250 +2,32 @@ from __future__ import annotationsimport jsonimport logging-import refrom pathlib import Pathfrom typing import Anyimport anyio-from langchain_core.messages import (- AIMessage,- BaseMessage,- HumanMessage,- SystemMessage,- ToolMessage,-)-logger = logging.getLogger(__name__)--MODELS_WITHOUT_TOOL_SUPPORT_PATTERNS = [- 'deepseek-reasoner',- 'deepseek-r1',- '.*gemma.*-it',-]---def is_model_without_tool_support(model_name: str) -> bool:- return any(re.match(pattern, model_name) for pattern in MODELS_WITHOUT_TOOL_SUPPORT_PATTERNS)---def extract_json_from_model_output(content: str | BaseMessage) -> dict:- """Extract JSON from model output, handling both plain JSON and code-block-wrapped JSON."""- try:- # Extract string content from BaseMessage if needed- content_str: str- if isinstance(content, BaseMessage):- # for langchain_core.messages.BaseMessage- msg_content = content.content- if isinstance(msg_content, list):- content_str = str(msg_content[0]) if msg_content else ''- else:- content_str = msg_content- else:- content_str = content- # If content is wrapped in code blocks, extract just the JSON part- if '```' in content_str:- # Find the JSON content between code blocks- content_str = content_str.split('```')[1]- # Remove language identifier if present (e.g., 'json\n')- if '\n' in content_str:- content_str = content_str.split('\n', 1)[1]-- # remove html-like tags before the first { and after the last }- # This handles cases like <|header_start|>assistant<|header_end|> and <function=AgentOutput>- # Only remove content before { if content doesn't already start with {- if not content_str.strip().startswith('{'):- content_str = re.sub(r'^.*?(?=\{)', '', content_str, flags=re.DOTALL)-- # Remove common HTML-like tags and patterns at the end, but be more conservative- # Look for patterns like </function>, <|header_start|>, etc. after the JSON- content_str = re.sub(r'\}(\s*<[^>]*>.*?$)', '}', content_str, flags=re.DOTALL)- content_str = re.sub(r'\}(\s*<\|[^|]*\|>.*?$)', '}', content_str, flags=re.DOTALL)-- # Handle extra characters after the JSON, including stray braces- # Find the position of the last } that would close the main JSON object- content_str = content_str.strip()-- if content_str.endswith('}'):- # Try to parse and see if we get valid JSON- try:- json.loads(content_str)- except json.JSONDecodeError:- # If parsing fails, try to find the correct end of the JSON- # by counting braces and removing anything after the balanced JSON- brace_count = 0- last_valid_pos = -1- for i, char in enumerate(content_str):- if char == '{':- brace_count += 1- elif char == '}':- brace_count -= 1- if brace_count == 0:- last_valid_pos = i + 1- break-- if last_valid_pos > 0:- content_str = content_str[:last_valid_pos]-- # Fix control characters in JSON strings before parsing- # This handles cases where literal control characters appear in JSON values- content_str = _fix_control_characters_in_json(content_str)-- # Parse the cleaned content- result_dict = json.loads(content_str)-- # if the key "function" and parameter key like "params"/"args"/"kwargs"/"parameters" are present, the final result is the value of the parameter key- if 'function' in result_dict:- params = result_dict.get(- 'params', result_dict.get('args', result_dict.get('kwargs', result_dict.get('parameters', {})))- )- if params:- result_dict = params- # some models occasionally respond with a list containing one dict: https://github.com/browser-use/browser-use/issues/1458- if isinstance(result_dict, list) and len(result_dict) == 1 and isinstance(result_dict[0], dict):- result_dict = result_dict[0]-- assert isinstance(result_dict, dict), f'Expected JSON dictionary in response, got JSON {type(result_dict)} instead'- logger.debug(f'Successfully parsed model output: {result_dict}')- return result_dict- except json.JSONDecodeError as e:- logger.warning(f'Failed to parse model output: {content} {str(e)}')- raise ValueError(f'Could not parse response. {str(e)}')---def _fix_control_characters_in_json(content: str) -> str:- """Fix control characters in JSON string values to make them valid JSON."""- try:- # First try to parse as-is to see if it's already valid- json.loads(content)- return content- except json.JSONDecodeError:- pass+from browser_use.llm.messages import BaseMessage- # More sophisticated approach: only escape control characters inside string values- # while preserving JSON structure formatting-- result = []- i = 0- in_string = False- escaped = False-- while i < len(content):- char = content[i]-- if not in_string:- # Outside of string - check if we're entering a string- if char == '"':- in_string = True- result.append(char)- else:- # Inside string - handle escaping and control characters- if escaped:- # Previous character was backslash, so this character is escaped- result.append(char)- escaped = False- elif char == '\\':- # This is an escape character- result.append(char)- escaped = True- elif char == '"':- # End of string- result.append(char)- in_string = False- elif char == '\n':- # Literal newline inside string - escape it- result.append('\\n')- elif char == '\r':- # Literal carriage return inside string - escape it- result.append('\\r')- elif char == '\t':- # Literal tab inside string - escape it- result.append('\\t')- elif char == '\b':- # Literal backspace inside string - escape it- result.append('\\b')- elif char == '\f':- # Literal form feed inside string - escape it- result.append('\\f')- elif ord(char) < 32:- # Other control characters inside string - convert to unicode escape- result.append(f'\\u{ord(char):04x}')- else:- # Normal character inside string- result.append(char)-- i += 1-- return ''.join(result)---def convert_input_messages(input_messages: list[BaseMessage], model_name: str | None) -> list[BaseMessage]:- """Convert input messages to a format that is compatible with the planner model"""- if model_name is None:- return input_messages-- # TODO: use the auto-detected tool calling method from Agent._set_tool_calling_method(),- # or abstract that logic out to reuse so we can autodetect the planner model's tool calling method as well- if is_model_without_tool_support(model_name):- converted_input_messages = _convert_messages_for_non_function_calling_models(input_messages)- merged_input_messages = _merge_successive_messages(converted_input_messages, HumanMessage)- merged_input_messages = _merge_successive_messages(merged_input_messages, AIMessage)- return merged_input_messages- return input_messages---def _convert_messages_for_non_function_calling_models(input_messages: list[BaseMessage]) -> list[BaseMessage]:- """Convert messages for non-function-calling models"""- output_messages = []- for message in input_messages:- if isinstance(message, HumanMessage):- output_messages.append(message)- elif isinstance(message, SystemMessage):- output_messages.append(message)- elif isinstance(message, ToolMessage):- output_messages.append(HumanMessage(content=message.content))- elif isinstance(message, AIMessage):- # check if tool_calls is a valid JSON object- if message.tool_calls:- tool_calls = json.dumps(message.tool_calls)- output_messages.append(AIMessage(content=tool_calls))- else:- output_messages.append(message)- else:- raise ValueError(f'Unknown message type: {type(message)}')- return output_messages---def _merge_successive_messages(messages: list[BaseMessage], class_to_merge: type[BaseMessage]) -> list[BaseMessage]:- """Some models like deepseek-reasoner dont allow multiple human messages in a row. This function merges them into one."""- merged_messages = []- streak = 0- for message in messages:- if isinstance(message, class_to_merge):- streak += 1- if streak > 1:- if isinstance(message.content, list):- merged_messages[-1].content += message.content[0]['text'] # type:ignore- else:- merged_messages[-1].content += message.content- else:- merged_messages.append(message)- else:- merged_messages.append(message)- streak = 0- return merged_messages+logger = logging.getLogger(__name__)async def save_conversation(- input_messages: list[BaseMessage], response: Any, target: str | Path, encoding: str | None = None+ input_messages: list[BaseMessage],+ response: Any,+ target: str | Path,+ encoding: str | None = None,) -> None:"""Save conversation history to file asynchronously."""target_path = Path(target)-# create folders if not existsif target_path.parent:await anyio.Path(target_path.parent).mkdir(parents=True, exist_ok=True)- await anyio.Path(target_path).write_text(await _format_conversation(input_messages, response), encoding=encoding or 'utf-8')+ await anyio.Path(target_path).write_text(+ await _format_conversation(input_messages, response),+ encoding=encoding or 'utf-8',+ )async def _format_conversation(messages: list[BaseMessage], response: Any) -> str:@@ -254,19 +36,9 @@ async def _format_conversation(messages: list[BaseMessage], response: Any) -> st# Format messagesfor message in messages:- lines.append(f' {message.__class__.__name__} ')-- if isinstance(message.content, list):- for item in message.content:- if isinstance(item, dict) and item.get('type') == 'text':- lines.append(item['text'].strip())- elif isinstance(message.content, str):- try:- content = json.loads(message.content)- lines.append(json.dumps(content, indent=2))- except json.JSONDecodeError:- lines.append(message.content.strip())+ lines.append(f' {message.role} ')+ lines.append(message.text)lines.append('') # Empty line after each message# Format responsediff --git a/browser_use/agent/message_manager/views.py b/browser_use/agent/message_manager/views.pyindex 67172c992..cac4124c3 100644--- a/browser_use/agent/message_manager/views.py+++ b/browser_use/agent/message_manager/views.py@@ -1,24 +1,25 @@from __future__ import annotations-from typing import TYPE_CHECKING, Any-from warnings import filterwarnings+from typing import TYPE_CHECKING, Literal-from langchain_core._api import LangChainBetaWarning-from langchain_core.load import dumpd, load-from langchain_core.messages import AIMessage, BaseMessage, HumanMessage, SystemMessage, ToolMessage-from pydantic import BaseModel, ConfigDict, Field, model_serializer, model_validator+from pydantic import BaseModel, ConfigDict, Field-filterwarnings('ignore', category=LangChainBetaWarning)+from browser_use.llm.messages import (+ BaseMessage,+ UserMessage,+)if TYPE_CHECKING:- from browser_use.agent.views import AgentOutput+ pass+++SupportedMessageTypes = Literal['init', 'memory']class MessageMetadata(BaseModel):"""Metadata for a message"""- tokens: int = 0- message_type: str | None = None+ message_type: SupportedMessageTypes | None = Noneclass ManagedMessage(BaseModel):@@ -27,50 +28,11 @@ class ManagedMessage(BaseModel):message: BaseMessagemetadata: MessageMetadata = Field(default_factory=MessageMetadata)- model_config = ConfigDict(arbitrary_types_allowed=True)-- # https://github.com/pydantic/pydantic/discussions/7558- @model_serializer(mode='wrap')- def to_json(self, original_dump):- """- Returns the JSON representation of the model.-- It uses langchain's `dumps` function to serialize the `message`- property before encoding the overall dict with json.dumps.- """- data = original_dump(self)-- # NOTE: We override the message field to use langchain JSON serialization.- data['message'] = dumpd(self.message)-- return data-- @model_validator(mode='before')- @classmethod- def validate(- cls,- value: Any,- *,- strict: bool | None = None,- from_attributes: bool | None = None,- context: Any | None = None,- ) -> Any:- """- Custom validator that uses langchain's `loads` function- to parse the message if it is provided as a JSON string.- """- if isinstance(value, dict) and 'message' in value:- # NOTE: We use langchain's load to convert the JSON string back into a BaseMessage object.- filterwarnings('ignore', category=LangChainBetaWarning)- value['message'] = load(value['message'])- return value-class MessageHistory(BaseModel):"""History of messages with metadata"""messages: list[ManagedMessage] = Field(default_factory=list)- current_tokens: int = 0model_config = ConfigDict(arbitrary_types_allowed=True)@@ -80,49 +42,14 @@ class MessageHistory(BaseModel):self.messages.append(ManagedMessage(message=message, metadata=metadata))else:self.messages.insert(position, ManagedMessage(message=message, metadata=metadata))- self.current_tokens += metadata.tokens-- def add_model_output(self, output: AgentOutput) -> None:- """Add model output as AI message"""- tool_calls = [- {- 'name': 'AgentOutput',- 'args': output.model_dump(mode='json', exclude_unset=True),- 'id': '1',- 'type': 'tool_call',- }- ]-- msg = AIMessage(- content='',- tool_calls=tool_calls,- )- self.add_message(msg, MessageMetadata(tokens=100)) # Estimate tokens for tool calls-- # Empty tool response- tool_message = ToolMessage(content='', tool_call_id='1')- self.add_message(tool_message, MessageMetadata(tokens=10)) # Estimate tokens for empty responsedef get_messages(self) -> list[BaseMessage]:"""Get all messages"""return [m.message for m in self.messages]- def get_total_tokens(self) -> int:- """Get total tokens in history"""- return self.current_tokens-- def remove_oldest_message(self) -> None:- """Remove oldest non-system message"""- for i, msg in enumerate(self.messages):- if not isinstance(msg.message, SystemMessage):- self.current_tokens -= msg.metadata.tokens- self.messages.pop(i)- break-def remove_last_state_message(self) -> None:"""Remove last state message from history"""- if len(self.messages) > 2 and isinstance(self.messages[-1].message, HumanMessage):- self.current_tokens -= self.messages[-1].metadata.tokens+ if len(self.messages) > 2 and isinstance(self.messages[-1].message, UserMessage):self.messages.pop()diff --git a/browser_use/agent/prompts.py b/browser_use/agent/prompts.pyindex 6f12b89de..3fb26d580 100644--- a/browser_use/agent/prompts.py+++ b/browser_use/agent/prompts.py@@ -2,7 +2,7 @@ import importlib.resourcesfrom datetime import datetimefrom typing import TYPE_CHECKING, Optional-from langchain_core.messages import HumanMessage, SystemMessage+from browser_use.llm.messages import ContentPartImageParam, ContentPartTextParam, ImageURL, SystemMessage, UserMessageif TYPE_CHECKING:from browser_use.agent.views import AgentStepInfo@@ -145,9 +145,9 @@ Interactive elements from top layer of the current page inside the viewport{truntime_str = datetime.now().strftime('%Y-%m-%d %H:%M')step_info_description += f'Current date and time: {time_str}'- todo_contents = self.file_system.get_todo_contents() if self.file_system else ''- if not len(todo_contents):- todo_contents = '[Current todo.md is empty, fill it with your plan when applicable]'+ _todo_contents = self.file_system.get_todo_contents() if self.file_system else ''+ if not len(_todo_contents):+ _todo_contents = '[Current todo.md is empty, fill it with your plan when applicable]'agent_state = f"""<user_request>@@ -157,7 +157,7 @@ Interactive elements from top layer of the current page inside the viewport{trun{self.file_system.describe() if self.file_system else 'No file system available'}</file_system><todo_contents>-{todo_contents}+{_todo_contents}</todo_contents>"""if self.sensitive_data:@@ -168,7 +168,7 @@ Interactive elements from top layer of the current page inside the viewport{trunagent_state += '<available_file_paths>\n' + '\n'.join(self.available_file_paths) + '\n</available_file_paths>\n'return agent_state- def get_user_message(self, use_vision: bool = True) -> HumanMessage:+ def get_user_message(self, use_vision: bool = True) -> UserMessage:state_description = ('<agent_history>\n'+ (self.agent_history_description.strip('\n') if self.agent_history_description else '')@@ -187,17 +187,19 @@ Interactive elements from top layer of the current page inside the viewport{trunif self.browser_state.screenshot and use_vision is True:# Format message for vision model- return HumanMessage(+ return UserMessage(content=[- {'type': 'text', 'text': state_description},- {- 'type': 'image_url',- 'image_url': {'url': f'data:image/png;base64,{self.browser_state.screenshot}'}, # , 'detail': 'low'- },+ ContentPartTextParam(text=state_description),+ ContentPartImageParam(+ image_url=ImageURL(+ url=f'data:image/png;base64,{self.browser_state.screenshot}',+ media_type='image/png',+ ),+ ),])- return HumanMessage(content=state_description)+ return UserMessage(content=state_description)class PlannerPrompt(SystemPrompt):@@ -206,7 +208,7 @@ class PlannerPrompt(SystemPrompt):def get_system_message(self, is_planner_reasoning: bool, extended_planner_system_prompt: str | None = None- ) -> SystemMessage | HumanMessage:+ ) -> SystemMessage | UserMessage:"""Get the system message for the planner.Args:@@ -245,6 +247,6 @@ Keep your responses concise and focused on actionable insights.planner_prompt_text += f'\n{extended_planner_system_prompt}'if is_planner_reasoning:- return HumanMessage(content=planner_prompt_text)+ return UserMessage(content=planner_prompt_text)else:return SystemMessage(content=planner_prompt_text)diff --git a/browser_use/agent/service.py b/browser_use/agent/service.pyindex ce4b3e8e9..c82701db8 100644--- a/browser_use/agent/service.py+++ b/browser_use/agent/service.py@@ -5,27 +5,16 @@ import jsonimport loggingimport osimport re-import shutilimport sysimport tempfileimport timeimport uuidfrom collections.abc import Awaitable, Callablefrom pathlib import Path-from threading import Threadfrom typing import Any, Generic, TypeVarfrom dotenv import load_dotenv-load_dotenv()--# from lmnr.sdk.decorators import observe-from bubus import EventBus-from langchain_core.language_models.chat_models import BaseChatModel-from langchain_core.messages import BaseMessage, HumanMessage, SystemMessage-from pydantic import BaseModel, ValidationError-from uuid_extensions import uuid7str-from browser_use.agent.cloud_events import (CreateAgentOutputFileEvent,CreateAgentSessionEvent,@@ -33,16 +22,27 @@ from browser_use.agent.cloud_events import (CreateAgentTaskEvent,UpdateAgentTaskEvent,)+from browser_use.llm.base import BaseChatModel+from browser_use.llm.messages import BaseMessage, UserMessage+from browser_use.tokens.service import TokenCost++load_dotenv()++# from lmnr.sdk.decorators import observe+from bubus import EventBus+from pydantic import ValidationError+from uuid_extensions import uuid7str+from browser_use.agent.gif import create_history_giffrom browser_use.agent.memory import Memory, MemoryConfig-from browser_use.agent.message_manager.service import MessageManager, MessageManagerSettings+from browser_use.agent.message_manager.service import (+ MessageManager,+ MessageManagerSettings,+)from browser_use.agent.message_manager.utils import (- convert_input_messages,- extract_json_from_model_output,- is_model_without_tool_support,save_conversation,)-from browser_use.agent.prompts import AgentMessagePrompt, PlannerPrompt, SystemPrompt+from browser_use.agent.prompts import PlannerPrompt, SystemPromptfrom browser_use.agent.views import (ActionResult,AgentError,@@ -54,7 +54,6 @@ from browser_use.agent.views import (AgentStepInfo,BrowserStateHistory,StepMetadata,- ToolCallingMethod,)from browser_use.browser import BrowserProfile, BrowserSessionfrom browser_use.browser.session import DEFAULT_BROWSER_PROFILE@@ -63,7 +62,10 @@ from browser_use.browser.views import BrowserStateSummaryfrom browser_use.config import CONFIGfrom browser_use.controller.registry.views import ActionModelfrom browser_use.controller.service import Controller-from browser_use.dom.history_tree_processor.service import DOMHistoryElement, HistoryTreeProcessor+from browser_use.dom.history_tree_processor.service import (+ DOMHistoryElement,+ HistoryTreeProcessor,+)from browser_use.exceptions import LLMExceptionfrom browser_use.filesystem.file_system import FileSystemfrom browser_use.sync import CloudSync@@ -72,7 +74,6 @@ from browser_use.telemetry.views import AgentTelemetryEventfrom browser_use.utils import (_log_pretty_path,get_browser_use_version,- handle_llm_error,time_execution_async,time_execution_sync,)@@ -145,7 +146,6 @@ class Agent(Generic[Context]):retry_delay: int = 10,override_system_message: str | None = None,extend_system_message: str | None = None,- max_input_tokens: int = 128000,validate_output: bool = False,message_context: str | None = None,generate_gif: bool | str = False,@@ -166,7 +166,6 @@ class Agent(Generic[Context]):'aria-checked',],max_actions_per_step: int = 1,- tool_calling_method: ToolCallingMethod | None = 'auto',page_extraction_llm: BaseChatModel | None = None,planner_llm: BaseChatModel | None = None,planner_interval: int = 1, # Run planner every N steps@@ -208,14 +207,12 @@ class Agent(Generic[Context]):retry_delay=retry_delay,override_system_message=override_system_message,extend_system_message=extend_system_message,- max_input_tokens=max_input_tokens,validate_output=validate_output,message_context=message_context,generate_gif=generate_gif,available_file_paths=available_file_paths,include_attributes=include_attributes,max_actions_per_step=max_actions_per_step,- tool_calling_method=tool_calling_method,page_extraction_llm=page_extraction_llm,planner_llm=planner_llm,planner_interval=planner_interval,@@ -223,6 +220,13 @@ class Agent(Generic[Context]):extend_planner_system_message=extend_planner_system_message,)+ # Token cost service+ self.token_cost_service = TokenCost()+ self.token_cost_service.register_llm(llm)+ self.token_cost_service.register_llm(page_extraction_llm)+ if self.settings.planner_llm:+ self.token_cost_service.register_llm(self.settings.planner_llm)+# Memory settingsself.enable_memory = enable_memoryself.memory_config = memory_config@@ -238,39 +242,35 @@ class Agent(Generic[Context]):self._set_browser_use_version_and_source(source)self.initial_actions = self._convert_initial_actions(initial_actions) if initial_actions else None- # Model setup- self._set_model_names()-# Verify we can connect to the LLM and setup the tool calling methodself._verify_and_setup_llm()+ # TODO: move this logic to the LLMs# Handle users trying to use use_vision=True with DeepSeek models- if 'deepseek' in self.model_name.lower():+ if 'deepseek' in self.llm.model.lower():self.logger.warning('⚠️ DeepSeek models do not support use_vision=True yet. Setting use_vision=False for now...')self.settings.use_vision = False- if 'deepseek' in (self.planner_model_name or '').lower():+ if self.settings.planner_llm and 'deepseek' in (self.settings.planner_llm.model or '').lower():self.logger.warning('⚠️ DeepSeek models do not support use_vision=True yet. Setting use_vision_for_planner=False for now...')self.settings.use_vision_for_planner = False# Handle users trying to use use_vision=True with XAI models- if 'grok' in self.model_name.lower():+ if 'grok' in self.llm.model.lower():self.logger.warning('⚠️ XAI models do not support use_vision=True yet. Setting use_vision=False for now...')self.settings.use_vision = False- if 'grok' in (self.planner_model_name or '').lower():+ if self.settings.planner_llm and 'grok' in (self.settings.planner_llm.model or '').lower():self.logger.warning('⚠️ XAI models do not support use_vision=True yet. Setting use_vision_for_planner=False for now...')self.settings.use_vision_for_planner = Falseself.logger.info(- f'🧠 Starting a browser-use agent {self.version} with base_model={self.model_name}'- f'{" +tools" if self.tool_calling_method == "function_calling" else ""}'- f'{" +rawtools" if self.tool_calling_method == "raw" else ""}'+ f'🧠 Starting a browser-use agent {self.version} with base_model={self.llm.model}'f'{" +vision" if self.settings.use_vision else ""}'f'{" +memory" if self.enable_memory else ""}'- f' extraction_model={getattr(self.settings.page_extraction_llm, "model_name", None)}'- f'{f" planner_model={self.planner_model_name}" if self.planner_model_name else ""}'+ f' extraction_model={self.settings.page_extraction_llm.model if self.settings.page_extraction_llm else "Unknown"}'+ f'{f" planner_model={self.settings.planner_llm.model}" if self.settings.planner_llm else ""}'f'{" +reasoning" if self.settings.is_planner_reasoning else ""}'f'{" +vision" if self.settings.use_vision_for_planner else ""} 'f'{" +file_system" if self.file_system else ""}'@@ -280,8 +280,6 @@ class Agent(Generic[Context]):# These will be used for the system prompt to maintain cachingself.unfiltered_actions = self.controller.registry.get_prompt_description()- self.settings.message_context = self._set_message_context()-# Initialize message manager with state# Initial system prompt with all actions - will be updated during each stepself._message_manager = MessageManager(@@ -294,7 +292,6 @@ class Agent(Generic[Context]):).get_system_message(),file_system=self.file_system,settings=MessageManagerSettings(- max_input_tokens=self.settings.max_input_tokens,include_attributes=self.settings.include_attributes,message_context=self.settings.message_context,sensitive_data=sensitive_data,@@ -304,7 +301,8 @@ class Agent(Generic[Context]):state=self.state.message_manager_state,)- if self.enable_memory:+ # TODO: FIX MEMORY+ if self.enable_memory and False:try:# Initialize memoryself.memory = Memory(@@ -494,13 +492,47 @@ class Agent(Generic[Context]):logger.info(f'💾 File system path: {self.file_system_path}')- def _set_message_context(self) -> str | None:- if self.tool_calling_method == 'raw':- # For raw tool calling, only include actions with no filters initially- if self.settings.message_context:- self.settings.message_context += f'\n\nAvailable actions: {self.unfiltered_actions}'+ # TODO: move this logic to special registries -> we have methods to combine controllers++ # if file system is set, add actions to the controller+ @self.controller.registry.action('Write content to file_name in file system, use only .md or .txt extensions.')+ async def write_file(file_name: str, content: str):+ result = await self.file_system.write_file(file_name, content)+ logger.info(f'💾 {result}')+ return ActionResult(+ extracted_content=result,+ include_in_memory=True,+ long_term_memory=result,+ )++ @self.controller.registry.action('Append content to file_name in file system')+ async def append_file(file_name: str, content: str):+ result = await self.file_system.append_file(file_name, content)+ logger.info(f'💾 {result}')+ return ActionResult(+ extracted_content=result,+ include_in_memory=True,+ long_term_memory=result,+ )++ @self.controller.registry.action('Read file_name from file system')+ async def read_file(file_name: str):+ result = await self.file_system.read_file(file_name)+ max_len = 50+ if len(result) > max_len:+ display_result = result[:max_len] + '\n...'else:- self.settings.message_context = f'Available actions: {self.unfiltered_actions}'+ display_result = result+ logger.info(f'💾 {display_result}')+ memory = result.split('\n')[-1]+ return ActionResult(+ extracted_content=result,+ include_in_memory=True,+ long_term_memory=memory,+ include_extracted_content_only_once=True,+ )++ def _set_message_context(self) -> str | None:return self.settings.message_contextdef _set_browser_use_version_and_source(self, source_override: str | None = None) -> None:@@ -526,25 +558,19 @@ class Agent(Generic[Context]):self.version = versionself.source = source- def _set_model_names(self) -> None:- self.chat_model_library = self.llm.__class__.__name__- self.model_name = 'Unknown'- if hasattr(self.llm, 'model_name'):- model = self.llm.model_name # type: ignore- self.model_name = model if model is not None else 'Unknown'- elif hasattr(self.llm, 'model'):- model = self.llm.model # type: ignore- self.model_name = model if model is not None else 'Unknown'+ # def _set_model_names(self) -> None:+ # self.chat_model_library = self.llm.provider+ # self.model_name = self.llm.model- if self.settings.planner_llm:- if hasattr(self.settings.planner_llm, 'model_name'):- self.planner_model_name = self.settings.planner_llm.model_name # type: ignore- elif hasattr(self.settings.planner_llm, 'model'):- self.planner_model_name = self.settings.planner_llm.model # type: ignore- else:- self.planner_model_name = 'Unknown'- else:- self.planner_model_name = None+ # if self.settings.planner_llm:+ # if hasattr(self.settings.planner_llm, 'model_name'):+ # self.planner_model_name = self.settings.planner_llm.model_name # type: ignore+ # elif hasattr(self.settings.planner_llm, 'model'):+ # self.planner_model_name = self.settings.planner_llm.model # type: ignore+ # else:+ # self.planner_model_name = 'Unknown'+ # else:+ # self.planner_model_name = Nonedef _setup_action_models(self) -> None:"""Setup dynamic action models from controller's registry"""@@ -557,285 +583,6 @@ class Agent(Generic[Context]):self.DoneActionModel = self.controller.registry.create_action_model(include_actions=['done'])self.DoneAgentOutput = AgentOutput.type_with_custom_actions(self.DoneActionModel)- def _test_tool_calling_method(self, method: str | None) -> bool:- """Test if a specific tool calling method works with the current LLM."""- try:- # Test configuration- CAPITAL_QUESTION = 'What is the capital of France? Respond with just the city name in lowercase.'- EXPECTED_ANSWER = 'paris'-- class CapitalResponse(BaseModel):- """Response model for capital city question"""-- answer: str # The name of the capital city in lowercase-- def is_valid_raw_response(response, expected_answer: str) -> bool:- """- Cleans and validates a raw JSON response string against an expected answer.- """- content = getattr(response, 'content', '').strip()- # self.logger.debug(f'Raw response content: {content}')-- # Remove surrounding markdown code blocks if present- if content.startswith('```json') and content.endswith('```'):- content = content[7:-3].strip()- elif content.startswith('```') and content.endswith('```'):- content = content[3:-3].strip()-- # Attempt to parse and validate the answer- try:- result = json.loads(content)- answer = str(result.get('answer', '')).strip().lower().strip(' .')-- if expected_answer.lower() not in answer:- self.logger.debug(f"🛠️ Tool calling method {method} failed: expected '{expected_answer}', got '{answer}'")- return False-- return True-- except (json.JSONDecodeError, AttributeError, TypeError) as e:- self.logger.debug(f'🛠️ Tool calling method {method} failed: Failed to parse JSON content: {e}')- return False-- if method == 'raw' or method == 'json_mode':- # For raw mode, test JSON response format- test_prompt = f"""{CAPITAL_QUESTION}- Respond with a json object like: {{"answer": "city_name_in_lowercase"}}"""-- response = self.llm.invoke([test_prompt])- # Basic validation of response- if not response or not hasattr(response, 'content'):- return False-- if not is_valid_raw_response(response, EXPECTED_ANSWER):- return False- return True- else:- # For other methods, try to use structured output- structured_llm = self.llm.with_structured_output(CapitalResponse, include_raw=True, method=method)- response = structured_llm.invoke([HumanMessage(content=CAPITAL_QUESTION)])-- if not response:- self.logger.debug(f'🛠️ Tool calling method {method} failed: empty response')- return False-- def extract_parsed(response: Any) -> CapitalResponse | None:- if isinstance(response, dict):- return response.get('parsed')- return getattr(response, 'parsed', None)-- parsed = extract_parsed(response)-- if not isinstance(parsed, CapitalResponse):- self.logger.debug(f'🛠️ Tool calling method {method} failed: LLM responded with invalid JSON')- return False-- if EXPECTED_ANSWER not in parsed.answer.lower():- self.logger.debug(f'🛠️ Tool calling method {method} failed: LLM failed to answer test question correctly')- return False- return True-- except Exception as e:- self.logger.debug(f"🛠️ Tool calling method '{method}' test failed: {type(e).__name__}: {str(e)}")- return False-- async def _test_tool_calling_method_async(self, method: str) -> tuple[str, bool]:- """Test if a specific tool calling method works with the current LLM (async version)."""- # Run the synchronous test in a thread pool to avoid blocking- loop = asyncio.get_event_loop()- result = await loop.run_in_executor(None, self._test_tool_calling_method, method)- return (method, result)-- def _detect_best_tool_calling_method(self) -> str | None:- """Detect the best supported tool calling method by testing each one."""- start_time = time.time()-- # Order of preference for tool calling methods- methods_to_try = [- 'function_calling', # Most capable and efficient- 'tools', # Works with some models that don't support function_calling- 'json_mode', # More basic structured output- 'raw', # Fallback - no tool calling support- ]-- # Try parallel testing for faster detection- try:- # Run async parallel tests- async def test_all_methods():- tasks = [self._test_tool_calling_method_async(method) for method in methods_to_try]- results = await asyncio.gather(*tasks, return_exceptions=True)- return results-- # Execute async tests- try:- loop = asyncio.get_running_loop()- # Running loop: create a new loop in a separate thread- result = {}-- def run_in_thread():- new_loop = asyncio.new_event_loop()- asyncio.set_event_loop(new_loop)- try:- result['value'] = new_loop.run_until_complete(test_all_methods())- except Exception as e:- result['error'] = e- finally:- new_loop.close()-- t = Thread(target=run_in_thread)- t.start()- t.join()- if 'error' in result:- raise result['error']- results = result['value']-- except RuntimeError as e:- if 'no running event loop' in str(e):- results = asyncio.run(test_all_methods())- else:- raise-- # Process results in order of preference- for i, method in enumerate(methods_to_try):- if not isinstance(results, list):- continue- ith_result = results[i]- if isinstance(ith_result, tuple) and ith_result[1]: # (method, success)- setattr(self.llm, '_verified_api_keys', True)- setattr(self.llm, '_verified_tool_calling_method', method) # Cache on LLM instance- elapsed = time.time() - start_time- self.logger.debug(f'🛠️ Tested LLM in parallel and chose tool calling method: [{method}] in {elapsed:.2f}s')- return method-- except Exception as e:- self.logger.debug(f'Parallel testing failed: {e}, falling back to sequential')- # Fall back to sequential testing- for method in methods_to_try:- if self._test_tool_calling_method(method):- # if we found the method which means api is verified.- setattr(self.llm, '_verified_api_keys', True)- setattr(self.llm, '_verified_tool_calling_method', method) # Cache on LLM instance- elapsed = time.time() - start_time- self.logger.debug(f'🛠️ Tested LLM and chose tool calling method: [{method}] in {elapsed:.2f}s')- return method-- # If we get here, no methods worked- raise ConnectionError('Failed to connect to LLM. Please check your API key and network connection.')-- def _get_known_tool_calling_method(self) -> str | None:- """Get known tool calling method for common model/library combinations."""- # Fast path for known combinations- model_lower = self.model_name.lower()-- # OpenAI models- if self.chat_model_library == 'ChatOpenAI':- if any(m in model_lower for m in ['gpt-4', 'gpt-3.5']):- return 'function_calling'- if any(m in model_lower for m in ['llama-4', 'llama-3']):- return 'function_calling'-- elif self.chat_model_library == 'ChatGroq':- if any(m in model_lower for m in ['llama-4', 'llama-3']):- return 'function_calling'-- # Azure OpenAI models- elif self.chat_model_library == 'AzureChatOpenAI':- if 'gpt-4-' in model_lower:- return 'tools'- else:- return 'function_calling'-- # Google models- elif self.chat_model_library == 'ChatGoogleGenerativeAI':- return None # Google uses native tool support-- # Anthropic models- elif self.chat_model_library in ['ChatAnthropic', 'AnthropicChat']:- if any(m in model_lower for m in ['claude-3', 'claude-2']):- return 'tools'-- # Models known to not support tools- elif is_model_without_tool_support(self.model_name):- return 'raw'-- return None # Unknown combination, needs testing-- def _set_tool_calling_method(self) -> ToolCallingMethod | None:- """Determine the best tool calling method to use with the current LLM."""-- # old hardcoded logic- # if is_model_without_tool_support(self.model_name):- # return 'raw'- # elif self.chat_model_library == 'ChatGoogleGenerativeAI':- # return None- # elif self.chat_model_library == 'ChatOpenAI':- # return 'function_calling'- # elif self.chat_model_library == 'AzureChatOpenAI':- # # Azure OpenAI API requires 'tools' parameter for GPT-4- # # The error 'content must be either a string or an array' occurs when- # # the API expects a tools array but gets something else- # if 'gpt-4-' in self.model_name.lower():- # return 'tools'- # else:- # return 'function_calling'-- # If a specific method is set, use it- if self.settings.tool_calling_method != 'auto':- # Skip test if already verified- if getattr(self.llm, '_verified_api_keys', None) is True or CONFIG.SKIP_LLM_API_KEY_VERIFICATION:- setattr(self.llm, '_verified_api_keys', True)- setattr(self.llm, '_verified_tool_calling_method', self.settings.tool_calling_method)- return self.settings.tool_calling_method-- if not self._test_tool_calling_method(self.settings.tool_calling_method):- if self.settings.tool_calling_method == 'raw':- # if raw failed means error in API key or network connection- raise ConnectionError('Failed to connect to LLM. Please check your API key and network connection.')- else:- raise RuntimeError(- f"Configured tool calling method '{self.settings.tool_calling_method}' "- 'is not supported by the current LLM.'- )- setattr(self.llm, '_verified_tool_calling_method', self.settings.tool_calling_method)- return self.settings.tool_calling_method-- # Check if we already have a cached method on this LLM instance- if hasattr(self.llm, '_verified_tool_calling_method'):- self.logger.debug(- f'🛠️ Using cached tool calling method for {self.chat_model_library}/{self.model_name}: [{getattr(self.llm, "_verified_tool_calling_method")}]'- )- return getattr(self.llm, '_verified_tool_calling_method')-- # Try fast path for known model/library combinations- known_method = self._get_known_tool_calling_method()- if known_method is not None:- # Trust known combinations without testing if verification is already done or skipped- if getattr(self.llm, '_verified_api_keys', None) is True or CONFIG.SKIP_LLM_API_KEY_VERIFICATION:- setattr(self.llm, '_verified_api_keys', True)- setattr(self.llm, '_verified_tool_calling_method', known_method) # Cache on LLM instance- self.logger.debug(- f'🛠️ Using known tool calling method for {self.chat_model_library}/{self.model_name}: [{known_method}] (skipped test)'- )- return known_method # type: ignore-- start_time = time.time()- # Verify the known method works- if self._test_tool_calling_method(known_method):- setattr(self.llm, '_verified_api_keys', True)- setattr(self.llm, '_verified_tool_calling_method', known_method) # Cache on LLM instance- elapsed = time.time() - start_time- self.logger.debug(- f'🛠️ Using known tool calling method for {self.chat_model_library}/{self.model_name}: [{known_method}] in {elapsed:.2f}s'- )- return known_method # type: ignore- # If known method fails, fall back to detection- self.logger.debug(- f'Known method {known_method} failed for {self.chat_model_library}/{self.model_name}, falling back to detection'- )-- # Auto-detect the best method- return self._detect_best_tool_calling_method() # type: ignore-def add_new_task(self, new_task: str) -> None:"""Add a new task to the agent, keeping the same task_id as tasks are continuous"""# Simply delegate to message manager - no need for new task_id or events@@ -862,7 +609,6 @@ class Agent(Generic[Context]):model_output = Noneresult: list[ActionResult] = []step_start_time = time.time()- tokens = 0try:assert self.browser_session is not None, 'BrowserSession is not set up'@@ -886,24 +632,7 @@ class Agent(Generic[Context]):# If there are page-specific actions, add them as a special message for this step onlyif page_filtered_actions:page_action_message = f'For this page, these additional actions are available:\n{page_filtered_actions}'- self._message_manager._add_message_with_tokens(HumanMessage(content=page_action_message))-- # If using raw tool calling method, we need to update the message context with new actions- if self.tool_calling_method == 'raw':- # For raw tool calling, get all non-filtered actions plus the page-filtered ones- all_unfiltered_actions = self.controller.registry.get_prompt_description()- all_actions = all_unfiltered_actions- if page_filtered_actions:- all_actions += '\n' + page_filtered_actions-- context_lines = (self._message_manager.settings.message_context or '').split('\n')- non_action_lines = [line for line in context_lines if not line.startswith('Available actions:')]- updated_context = '\n'.join(non_action_lines)- if updated_context:- updated_context += f'\n\nAvailable actions: {all_actions}'- else:- updated_context = f'Available actions: {all_actions}'- self._message_manager.settings.message_context = updated_context+ self._message_manager._add_message_with_type(UserMessage(content=page_action_message))self._message_manager.add_state_message(browser_state_summary=browser_state_summary,@@ -928,11 +657,10 @@ class Agent(Generic[Context]):msg += '\nIf the task is fully finished, set success in "done" to true.'msg += '\nInclude everything you found out for the ultimate task in the done text.'self.logger.info('Last step finishing up')- self._message_manager._add_message_with_tokens(HumanMessage(content=msg))+ self._message_manager._add_message_with_type(UserMessage(content=msg))self.AgentOutput = self.DoneAgentOutputinput_messages = self._message_manager.get_messages()- tokens = self._message_manager.state.history.current_tokenstry:model_output = await self.get_next_action(input_messages)@@ -943,7 +671,7 @@ class Agent(Generic[Context]):):self.logger.warning('Model returned empty action. Retrying...')- clarification_message = HumanMessage(+ clarification_message = UserMessage(content='You forgot to return an action. Please respond only with a valid JSON action according to the expected format.')@@ -978,14 +706,18 @@ class Agent(Generic[Context]):conversation_dir = Path(self.settings.save_conversation_path)conversation_filename = f'conversation_{self.id}_{self.state.n_steps}.txt'target = conversation_dir / conversation_filename- await save_conversation(input_messages, model_output, target, self.settings.save_conversation_path_encoding)+ await save_conversation(+ input_messages,+ model_output,+ target,+ self.settings.save_conversation_path_encoding,+ )self._message_manager._remove_last_state_message() # we dont want the whole state in the chat history# check again if Ctrl+C was pressed before we commit the output to historyawait self._raise_if_stopped_or_paused()- # self._message_manager.add_model_output(model_output)except asyncio.CancelledError:# Task was cancelled due to Ctrl+Cself._message_manager._remove_last_state_message()@@ -1017,7 +749,8 @@ class Agent(Generic[Context]):# self.logger.debug('Agent paused')self.state.last_result = [ActionResult(- error='The agent was paused mid-step - the last action might need to be repeated', include_in_memory=True+ error='The agent was paused mid-step - the last action might need to be repeated',+ include_in_memory=True,)]return@@ -1040,7 +773,6 @@ class Agent(Generic[Context]):step_number=self.state.n_steps,step_start_time=step_start_time,step_end_time=step_end_time,- input_tokens=tokens,)self._make_history_item(model_output, browser_state_summary, result, metadata)@@ -1070,20 +802,29 @@ class Agent(Generic[Context]):if 'Browser closed' in error_msg:self.logger.error('❌ Browser is closed or disconnected, unable to proceed')- return [ActionResult(error='Browser closed or disconnected, unable to proceed', include_in_memory=True)]+ return [+ ActionResult(+ error='Browser closed or disconnected, unable to proceed',+ include_in_memory=True,+ )+ ]if isinstance(error, (ValidationError, ValueError)):self.logger.error(f'{prefix}{error_msg}')if 'Max token limit reached' in error_msg:# cut tokens from history- self._message_manager.settings.max_input_tokens = self.settings.max_input_tokens - 500- self.logger.info(- f'Cutting tokens from history - new max input tokens: {self._message_manager.settings.max_input_tokens}'- )- self._message_manager.cut_messages()+ # self._message_manager.settings.max_input_tokens = self.settings.max_input_tokens - 500+ # self.logger.info(+ # f'Cutting tokens from history - new max input tokens: {self._message_manager.settings.max_input_tokens}'+ # )+ # TODO: figure out what to do here+ pass++ # no longer cutting messages, because we revamped the message manager+ # self._message_manager.cut_messages()elif 'Could not parse response' in error_msg or 'tool_use_failed' in error_msg:# give model a hint how output should look like- logger.debug(f'Tool calling method: {self.tool_calling_method} with model: {self.model_name} failed')+ logger.debug(f'Model: {self.llm.model} failed')error_msg += '\n\nReturn a valid JSON object with the required fields.'logger.error(f'{prefix}{error_msg}')@@ -1129,7 +870,12 @@ class Agent(Generic[Context]):screenshot=browser_state_summary.screenshot,)- history_item = AgentHistory(model_output=model_output, result=result, state=state_history, metadata=metadata)+ history_item = AgentHistory(+ model_output=model_output,+ result=result,+ state=state_history,+ metadata=metadata,+ )self.state.history.history.append(history_item)@@ -1144,85 +890,12 @@ class Agent(Generic[Context]):text = re.sub(self.STRAY_CLOSE_TAG, '', text)return text.strip()- def _convert_input_messages(self, input_messages: list[BaseMessage]) -> list[BaseMessage]:- """Convert input messages to the correct format"""- if is_model_without_tool_support(self.model_name):- return convert_input_messages(input_messages, self.model_name)- else:- return input_messages-@time_execution_async('--get_next_action')async def get_next_action(self, input_messages: list[BaseMessage]) -> AgentOutput:"""Get next action from LLM based on current state"""- input_messages = self._convert_input_messages(input_messages)-- if self.tool_calling_method == 'raw':- self._log_llm_call_info(input_messages, self.tool_calling_method)- try:- output = await self.llm.ainvoke(input_messages)- response = {'raw': output, 'parsed': None}- except Exception as e:- self.logger.error(f'Failed to invoke model: {str(e)}')- # Extract status code if available (e.g., from HTTP exceptions)- status_code = getattr(e, 'status_code', None) or getattr(e, 'code', None) or 500- error_msg = f'LLM API call failed: {type(e).__name__}: {str(e)}'- raise LLMException(status_code, error_msg) from e- # TODO: currently invoke does not return reasoning_content, we should override invoke- output.content = self._remove_think_tags(str(output.content))- try:- parsed_json = extract_json_from_model_output(output.content)- parsed = self.AgentOutput(**parsed_json)- response['parsed'] = parsed- except (ValueError, ValidationError) as e:- logger.warning(f'Failed to parse model output: {output} {str(e)}')- raise ValueError('Could not parse response.' + str(e))-- elif self.tool_calling_method is None:- structured_llm = self.llm.with_structured_output(self.AgentOutput, include_raw=True)- try:- response: dict[str, Any] = await structured_llm.ainvoke(input_messages) # type: ignore- parsed: AgentOutput | None = response['parsed']-- except Exception as e:- response, raw = handle_llm_error(e)-- else:- try:- self._log_llm_call_info(input_messages, self.tool_calling_method)- structured_llm = self.llm.with_structured_output(- self.AgentOutput, include_raw=True, method=self.tool_calling_method- )- response: dict[str, Any] = await structured_llm.ainvoke(input_messages) # type: ignore- except Exception as e:- response, raw = handle_llm_error(e)-- # Handle tool call responses- if response.get('parsing_error') and 'raw' in response:- raw_msg = response['raw']- parsing_error = response.get('parsing_error')- if hasattr(raw_msg, 'tool_calls') and raw_msg.tool_calls:- # Convert tool calls to AgentOutput format- tool_call = raw_msg.tool_calls[0] # Take first tool call- tool_call_args = tool_call['args']- parsed = self.AgentOutput(**tool_call_args)-- try:- action = parsed.action[0].model_dump(exclude_unset=True)- except Exception as e:- raise ValueError(f'Could not parse response. {parsing_error} tried to parse {response["raw"]} to {parsed}')-- else:- parsed = None- else:- parsed = response['parsed']- if not parsed:- try:- parsed_json = extract_json_from_model_output(response['raw'])- parsed = self.AgentOutput(**parsed_json)- except Exception as e:- logger.warning(f'Failed to parse model output: {response["raw"]} {str(e)}')- raise ValueError(f'Could not parse response. {str(e)}')+ response = await self.llm.ainvoke(input_messages, output_format=self.AgentOutput)+ parsed = response.completion# cut the number of actions to max_actions_per_step if neededif len(parsed.action) > self.settings.max_actions_per_step:@@ -1311,41 +984,11 @@ class Agent(Generic[Context]):self.logger.info(f'📍 Step {self.state.n_steps}: Ran {action_count} actions in {step_duration:.2f}s: {status_str}')- def _log_llm_call_info(self, input_messages: list[BaseMessage], method: str) -> None:- """Log comprehensive information about the LLM call being made"""- # Count messages and check for images- message_count = len(input_messages)- total_chars = sum(len(str(msg.content)) for msg in input_messages)- has_images = any(- hasattr(msg, 'content')- and isinstance(msg.content, list)- and any(isinstance(item, dict) and item.get('type') == 'image_url' for item in msg.content)- for msg in input_messages- )- current_tokens = getattr(self._message_manager.state.history, 'current_tokens', 0)-- # Count available tools/actions from the current ActionModel- # This gives us the actual number of tools exposed to the LLM for this specific call- tool_count = len(self.ActionModel.model_fields) if hasattr(self, 'ActionModel') else 0-- # Format the log message parts- image_status = ', 📷 img' if has_images else ''- if method == 'raw':- output_format = '=> raw text'- tool_info = ''- else:- output_format = '=> JSON out'- tool_info = f' + 🔨 {tool_count} tools ({method})'-- term_width = shutil.get_terminal_size((80, 20)).columns- print('=' * term_width)- self.logger.info(- f'🧠 LLM call => {self.chat_model_library} [✉️ {message_count} msg, ~{current_tokens} tk, {total_chars} char{image_status}] {output_format}{tool_info}'- )-def _log_agent_event(self, max_steps: int, agent_run_error: str | None = None) -> None:"""Sent the agent event for this run to telemetry"""+ total_input_tokens = self.token_cost_service.get_usage_summary(calculate_cost=False).total_prompt_tokens+# Prepare action_history data correctlyaction_history_data = []for item in self.state.history.history:@@ -1367,9 +1010,9 @@ class Agent(Generic[Context]):self.telemetry.capture(AgentTelemetryEvent(task=self.task,- model=self.model_name,- model_provider=self.chat_model_library,- planner_llm=self.planner_model_name,+ model=self.llm.model,+ model_provider=self.llm.provider,+ planner_llm=self.settings.planner_llm.model if self.settings.planner_llm else None,max_steps=max_steps,max_actions_per_step=self.settings.max_actions_per_step,use_vision=self.settings.use_vision,@@ -1380,7 +1023,7 @@ class Agent(Generic[Context]):action_history=action_history_data,urls_visited=self.state.history.urls(),steps=self.state.n_steps,- total_input_tokens=self.state.history.total_input_tokens(),+ total_input_tokens=total_input_tokens,total_duration_seconds=self.state.history.total_duration_seconds(),success=self.state.history.is_successful(),final_result_response=final_result_str,@@ -1392,15 +1035,11 @@ class Agent(Generic[Context]):"""Take a stepReturns:- Tuple[bool, bool]: (is_done, is_valid)+ Tuple[bool, bool]: (is_done, is_valid)"""await self.step()if self.state.history.is_done():- if self.settings.validate_output:- if not await self._validate_output():- return True, False-await self.log_completion()if self.register_done_callback:if inspect.iscoroutinefunction(self.register_done_callback):@@ -1414,7 +1053,10 @@ class Agent(Generic[Context]):# @observe(name='agent.run', ignore_output=True)@time_execution_async('--run')async def run(- self, max_steps: int = 100, on_step_start: AgentHookFunc | None = None, on_step_end: AgentHookFunc | None = None+ self,+ max_steps: int = 100,+ on_step_start: AgentHookFunc | None = None,+ on_step_end: AgentHookFunc | None = None,) -> AgentHistoryList:"""Execute the task with maximum number of steps"""@@ -1494,10 +1136,6 @@ class Agent(Generic[Context]):await on_step_end(self)if self.state.history.is_done():- if self.settings.validate_output and step < max_steps - 1:- if not await self._validate_output():- continue-await self.log_completion()# Task completed@@ -1536,6 +1174,9 @@ class Agent(Generic[Context]):raise efinally:+ # Log token usage summary+ await self.token_cost_service.log_usage_summary()+# Unregister signal handlers before cleanupsignal_handler.unregister()@@ -1611,7 +1252,13 @@ class Agent(Generic[Context]):if orig_target_hash != new_target_hash:msg = f'Element index changed after action {i} / {len(actions)}, because page changed.'logger.info(msg)- results.append(ActionResult(extracted_content=msg, include_in_memory=True, long_term_memory=msg))+ results.append(+ ActionResult(+ extracted_content=msg,+ include_in_memory=True,+ long_term_memory=msg,+ )+ )breaknew_path_hashes = {e.hash.branch_path_hash for e in new_selector_map.values()}@@ -1619,7 +1266,13 @@ class Agent(Generic[Context]):# next action requires index but there are new elements on the pagemsg = f'Something new appeared after action {i} / {len(actions)}, following actions are NOT executed and should be retried.'logger.info(msg)- results.append(ActionResult(extracted_content=msg, include_in_memory=True, long_term_memory=msg))+ results.append(+ ActionResult(+ extracted_content=msg,+ include_in_memory=True,+ long_term_memory=msg,+ )+ )breaktry:@@ -1653,57 +1306,16 @@ class Agent(Generic[Context]):self.logger.info(f'Action {i + 1} was cancelled due to Ctrl+C')if not results:# Add a result for the cancelled action- results.append(ActionResult(error='The action was cancelled due to Ctrl+C', include_in_memory=True))+ results.append(+ ActionResult(+ error='The action was cancelled due to Ctrl+C',+ include_in_memory=True,+ )+ )raise InterruptedError('Action cancelled by user')return results- async def _validate_output(self) -> bool:- """Validate the output of the last action is what the user wanted"""- system_msg = (- f'You are a validator of an agent who interacts with a browser. '- f'Validate if the output of last action is what the user wanted and if the task is completed. '- f'If the task is unclear defined, you can let it pass. But if something is missing or the image does not show what was requested dont let it pass. '- f'Try to understand the page and help the model with suggestions like scroll, do x, ... to get the solution right. '- f'Task to validate: {self.task}. Return a JSON object with 2 keys: is_valid and reason. '- f'is_valid is a boolean that indicates if the output is correct. '- f'reason is a string that explains why it is valid or not.'- f' example: {{"is_valid": false, "reason": "The user wanted to search for "cat photos", but the agent searched for "dog photos" instead."}}'- )-- if self.browser_context and self.browser_session:- browser_state_summary = await self.browser_session.get_state_summary(cache_clickable_elements_hashes=False)- assert browser_state_summary- content = AgentMessagePrompt(- browser_state_summary=browser_state_summary,- file_system=self.file_system,- include_attributes=self.settings.include_attributes,- )- msg = [SystemMessage(content=system_msg), content.get_user_message(self.settings.use_vision)]- else:- # if no browser session, we can't validate the output- return True-- class ValidationResult(BaseModel):- """- Validation results.- """-- is_valid: bool- reason: str-- validator = self.llm.with_structured_output(ValidationResult, include_raw=True)- response: dict[str, Any] = await validator.ainvoke(msg) # type: ignore- parsed: ValidationResult = response['parsed']- is_valid = parsed.is_valid- if not is_valid:- self.logger.info(f'❌ Validator decision: {parsed.reason}')- msg = f'The output is not yet correct. {parsed.reason}.'- self.state.last_result = [ActionResult(extracted_content=msg, include_in_memory=True, long_term_memory=msg)]- else:- self.logger.info(f'✅ Validator decision: {parsed.reason}')- return is_valid-async def log_completion(self) -> None:"""Log the completion of the task"""if self.state.history.is_successful():@@ -1711,9 +1323,6 @@ class Agent(Generic[Context]):else:self.logger.info('❌ Task completed without success')- total_tokens = self.state.history.total_input_tokens()- self.logger.debug(f'💲 Total input tokens used (approximate): {total_tokens}')-if self.register_done_callback:if inspect.iscoroutinefunction(self.register_done_callback):await self.register_done_callback(self.state.history)@@ -1731,13 +1340,13 @@ class Agent(Generic[Context]):Rerun a saved history of actions with error handling and retry logic.Args:- history: The history to replay- max_retries: Maximum number of retries per action- skip_failures: Whether to skip failed actions or stop execution- delay_between_actions: Delay between actions in seconds+ history: The history to replay+ max_retries: Maximum number of retries per action+ skip_failures: Whether to skip failed actions or stop execution+ delay_between_actions: Delay between actions in secondsReturns:- List of action results+ List of action results"""# Execute initial actions if providedif self.initial_actions:@@ -1835,8 +1444,8 @@ class Agent(Generic[Context]):Load history from file and rerun it.Args:- history_file: Path to the history file- **kwargs: Additional arguments passed to rerun_history+ history_file: Path to the history file+ **kwargs: Additional arguments passed to rerun_history"""if not history_file:history_file = 'AgentHistory.json'@@ -1920,7 +1529,6 @@ class Agent(Generic[Context]):Verify that the LLM API keys are setup and the LLM API is responding properly.Also handles tool calling method detection if in auto mode."""- self.tool_calling_method = self._set_tool_calling_method()# Skip verification if already doneif getattr(self.llm, '_verified_api_keys', None) is True or CONFIG.SKIP_LLM_API_KEY_VERIFICATION:@@ -1956,21 +1564,19 @@ class Agent(Generic[Context]):]if not self.settings.use_vision_for_planner and self.settings.use_vision:- last_state_message: HumanMessage = planner_messages[-1]+ last_state_message: UserMessage = planner_messages[-1]# remove image from last state messagenew_msg = ''if isinstance(last_state_message.content, list):for msg in last_state_message.content:- if msg['type'] == 'text': # type: ignore- new_msg += msg['text'] # type: ignore- elif msg['type'] == 'image_url': # type: ignore- continue # type: ignore+ if msg.type == 'text':+ new_msg += msg.text+ elif msg.type == 'image_url':+ continueelse:new_msg = last_state_message.content- planner_messages[-1] = HumanMessage(content=new_msg)-- planner_messages = convert_input_messages(planner_messages, self.planner_model_name)+ planner_messages[-1] = UserMessage(content=new_msg)# Get planner outputtry:@@ -1982,10 +1588,10 @@ class Agent(Generic[Context]):error_msg = f'Planner LLM API call failed: {type(e).__name__}: {str(e)}'raise LLMException(status_code, error_msg) from e- plan = str(response.content)+ plan = response.completion# if deepseek-reasoner, remove think tags- if self.planner_model_name and (- 'deepseek-r1' in self.planner_model_name or 'deepseek-reasoner' in self.planner_model_name+ if self.settings.planner_llm and (+ 'deepseek-r1' in self.settings.planner_llm.model or 'deepseek-reasoner' in self.settings.planner_llm.model):plan = self._remove_think_tags(plan)try:diff --git a/browser_use/agent/views.py b/browser_use/agent/views.pyindex 1f94edbaa..1e39bf4f0 100644--- a/browser_use/agent/views.py+++ b/browser_use/agent/views.py@@ -4,9 +4,8 @@ import jsonimport tracebackfrom dataclasses import dataclassfrom pathlib import Path-from typing import Any, Literal+from typing import Any-from langchain_core.language_models.chat_models import BaseChatModelfrom openai import RateLimitErrorfrom pydantic import BaseModel, ConfigDict, Field, ValidationError, create_model, model_validatorfrom uuid_extensions import uuid7str@@ -20,18 +19,7 @@ from browser_use.dom.history_tree_processor.service import (HistoryTreeProcessor,)from browser_use.dom.views import SelectorMap--ToolCallingMethod = Literal['function_calling', 'json_mode', 'raw', 'auto', 'tools']-REQUIRED_LLM_API_ENV_VARS = {- 'ChatOpenAI': ['OPENAI_API_KEY'],- 'AzureChatOpenAI': ['AZURE_OPENAI_ENDPOINT', 'AZURE_OPENAI_KEY'],- 'ChatBedrockConverse': ['ANTHROPIC_API_KEY'],- 'ChatAnthropic': ['ANTHROPIC_API_KEY'],- 'ChatGoogleGenerativeAI': ['GOOGLE_API_KEY'],- 'ChatDeepSeek': ['DEEPSEEK_API_KEY'],- 'ChatOllama': [],- 'ChatGrok': ['GROK_API_KEY'],-}+from browser_use.llm.base import BaseChatModelclass AgentSettings(BaseModel):@@ -43,7 +31,6 @@ class AgentSettings(BaseModel):save_conversation_path_encoding: str | None = 'utf-8'max_failures: int = 3retry_delay: int = 10- max_input_tokens: int = 128000validate_output: bool = Falsemessage_context: str | None = Nonegenerate_gif: bool | str = False@@ -64,7 +51,6 @@ class AgentSettings(BaseModel):]max_actions_per_step: int = 10- tool_calling_method: ToolCallingMethod | None = 'auto'page_extraction_llm: BaseChatModel | None = Noneplanner_llm: BaseChatModel | None = Noneplanner_interval: int = 1 # Run planner every N steps@@ -142,7 +128,6 @@ class StepMetadata(BaseModel):step_start_time: floatstep_end_time: float- input_tokens: int # Approximate tokens from message manager for this stepstep_number: int@property@@ -159,7 +144,7 @@ class AgentBrain(BaseModel):class AgentOutput(BaseModel):- model_config = ConfigDict(arbitrary_types_allowed=True)+ model_config = ConfigDict(arbitrary_types_allowed=True, extra='forbid')thinking: strevaluation_previous_goal: str@@ -255,22 +240,6 @@ class AgentHistoryList(BaseModel):total += h.metadata.duration_secondsreturn total- def total_input_tokens(self) -> int:- """- Get total tokens used across all steps.- Note: These are from the approximate token counting of the message manager.- For accurate token counting, use tools like LangChain Smith or OpenAI's token counters.- """- total = 0- for h in self.history:- if h.metadata:- total += h.metadata.input_tokens- return total-- def input_token_usage(self) -> list[int]:- """Get token usage for each step"""- return [h.metadata.input_tokens for h in self.history if h.metadata]-def __str__(self) -> str:"""Representation of the AgentHistoryList object"""return f'AgentHistoryList(all_results={self.action_results()}, all_model_outputs={self.model_actions()})'diff --git a/browser_use/browser/session.py b/browser_use/browser/session.pyindex 6d08d1e3f..0e89921a6 100644--- a/browser_use/browser/session.py+++ b/browser_use/browser/session.py@@ -1655,10 +1655,15 @@ class BrowserSession(BaseModel):# --- Page navigation ---@require_initializationasync def navigate(self, url: str) -> None:+ # Add https:// if there's no protocol+ normalized_url = url.strip()+ if '://' not in normalized_url:+ normalized_url = f'https://{normalized_url}'+if self.agent_current_page:- await self.agent_current_page.goto(url, wait_until='domcontentloaded')+ await self.agent_current_page.goto(normalized_url, wait_until='domcontentloaded')else:- await self.create_new_tab(url)+ await self.create_new_tab(normalized_url)@require_initializationasync def refresh(self) -> None:@@ -2168,11 +2173,17 @@ class BrowserSession(BaseModel):async def navigate_to(self, url: str):"""Navigate the agent's current tab to a URL"""- if not self._is_url_allowed(url):- raise BrowserError(f'Navigation to non-allowed URL: {url}')++ # Add https:// if there's no protocol+ normalized_url = url.strip()+ if '://' not in normalized_url:+ normalized_url = f'https://{normalized_url}'++ if not self._is_url_allowed(normalized_url):+ raise BrowserError(f'Navigation to non-allowed URL: {normalized_url}')page = await self.get_current_page()- await page.goto(url)+ await page.goto(normalized_url)try:await page.wait_for_load_state()except Exception as e:@@ -3017,8 +3028,15 @@ class BrowserSession(BaseModel):async def create_new_tab(self, url: str | None = None) -> Page:"""Create a new tab and optionally navigate to a URL"""- if url and not self._is_url_allowed(url):- raise BrowserError(f'Cannot create new tab with non-allowed URL: {url}')+ # Add https:// if there's no protocol+ normalized_url = url+ if url:+ normalized_url = url.strip()+ if '://' not in normalized_url:+ normalized_url = f'https://{normalized_url}'++ if not self._is_url_allowed(normalized_url):+ raise BrowserError(f'Cannot create new tab with non-allowed URL: {normalized_url}')try:assert self.browser_context is not None, 'Browser context is not set'@@ -3056,12 +3074,12 @@ class BrowserSession(BaseModel):if self.browser_profile.viewport:await new_page.set_viewport_size(self.browser_profile.viewport)- if url:+ if normalized_url:try:- await new_page.goto(url, wait_until='domcontentloaded')+ await new_page.goto(normalized_url, wait_until='domcontentloaded')await self._wait_for_page_and_frames_load(timeout_overwrite=1)except Exception as e:- self.logger.error(f'❌ Error navigating to {url}: {type(e).__name__}: {e} (proceeding anyway...)')+ self.logger.error(f'❌ Error navigating to {normalized_url}: {type(e).__name__}: {e} (proceeding anyway...)')assert self.human_current_page is not Noneassert self.agent_current_page is not Nonediff --git a/browser_use/cli.py b/browser_use/cli.pyindex dfc5c1775..8f5b4ebe0 100644--- a/browser_use/cli.py+++ b/browser_use/cli.py@@ -10,6 +10,10 @@ from typing import Anyfrom dotenv import load_dotenv+from browser_use.llm.anthropic.chat import ChatAnthropic+from browser_use.llm.google.chat import ChatGoogle+from browser_use.llm.openai.chat import ChatOpenAI+load_dotenv()try:@@ -23,9 +27,6 @@ except ImportError:print('⚠️ CLI addon is not installed. Please install it with: `pip install browser-use[cli]` and try again.')sys.exit(1)-import langchain_anthropic-import langchain_google_genai-import langchain_openaitry:import readline@@ -196,27 +197,25 @@ def get_llm(config: dict[str, Any]):if not CONFIG.OPENAI_API_KEY:print('⚠️ OpenAI API key not found. Please update your config or set OPENAI_API_KEY environment variable.')sys.exit(1)- return langchain_openai.ChatOpenAI(model=model_name, temperature=temperature)+ return ChatOpenAI(model=model_name, temperature=temperature)elif model_name.startswith('claude'):if not CONFIG.ANTHROPIC_API_KEY:print('⚠️ Anthropic API key not found. Please update your config or set ANTHROPIC_API_KEY environment variable.')sys.exit(1)- return langchain_anthropic.ChatAnthropic(model_name=model_name, temperature=temperature, timeout=30, stop=None)+ return ChatAnthropic(model=model_name, temperature=temperature)elif model_name.startswith('gemini'):if not CONFIG.GOOGLE_API_KEY:print('⚠️ Google API key not found. Please update your config or set GOOGLE_API_KEY environment variable.')sys.exit(1)- return langchain_google_genai.ChatGoogleGenerativeAI(model=model_name, temperature=temperature)+ return ChatGoogle(model=model_name, temperature=temperature)# Auto-detect based on available API keysif CONFIG.OPENAI_API_KEY:- return langchain_openai.ChatOpenAI(model='gpt-4o', temperature=temperature)+ return ChatOpenAI(model='gpt-4o', temperature=temperature)elif CONFIG.ANTHROPIC_API_KEY:- return langchain_anthropic.ChatAnthropic(- model_name='claude-3.5-sonnet-exp', temperature=temperature, timeout=30, stop=None- )+ return ChatAnthropic(model='claude-3.5-sonnet-exp', temperature=temperature)elif CONFIG.GOOGLE_API_KEY:- return langchain_google_genai.ChatGoogleGenerativeAI(model='gemini-2.0-flash-lite', temperature=temperature)+ return ChatGoogle(model='gemini-2.0-flash-lite', temperature=temperature)else:print('⚠️ No API keys found. Please update your config or set one of: OPENAI_API_KEY, ANTHROPIC_API_KEY, or GOOGLE_API_KEY.'@@ -485,7 +484,6 @@ class BrowserUseApp(App):'playwright','urllib3','asyncio',- 'langchain','openai','httpcore','charset_normalizer',@@ -802,28 +800,27 @@ class BrowserUseApp(App):# Show token usage statistics if agent exists and has historyif self.agent and hasattr(self.agent, 'state') and hasattr(self.agent.state, 'history'):# Get total tokens used- total_tokens = self.agent.state.history.total_input_tokens()- model_info.write(f'[white]Input tokens:[/] [green]{total_tokens:,}[/]')+ # total_tokens = self.agent.state.history.total_input_tokens()+ # model_info.write(f'[white]Input tokens:[/] [green]{total_tokens:,}[/]')# Calculate tokens per stepnum_steps = len(self.agent.state.history.history)- if num_steps > 0:- avg_tokens_per_step = total_tokens / num_steps- model_info.write(f'[white]Avg tokens/step:[/] [green]{avg_tokens_per_step:,.1f}[/]')+ # if num_steps > 0:+ # avg_tokens_per_step = total_tokens / num_steps+ # model_info.write(f'[white]Avg tokens/step:[/] [green]{avg_tokens_per_step:,.1f}[/]')- # Get the last step metadata to show the most recent LLM response time+ # Get the last step metadata to show the most recent LLM response timeif num_steps > 0 and self.agent.state.history.history[-1].metadata:last_step = self.agent.state.history.history[-1]if last_step.metadata:step_duration = last_step.metadata.duration_seconds- step_tokens = last_step.metadata.input_tokenselse:step_duration = 0- step_tokens = 0+ # step_tokens = last_step.metadata.input_tokens- if step_tokens > 0:- tokens_per_second = step_tokens / step_duration if step_duration > 0 else 0- model_info.write(f'[white]Avg tokens/sec:[/] [magenta]{tokens_per_second:.1f}[/]')+ # if step_tokens > 0:+ # tokens_per_second = step_tokens / step_duration if step_duration > 0 else 0+ # model_info.write(f'[white]Avg tokens/sec:[/] [magenta]{tokens_per_second:.1f}[/]')# Show total durationtotal_duration = self.agent.state.history.total_duration_seconds()diff --git a/browser_use/controller/registry/service.py b/browser_use/controller/registry/service.pyindex 86b6ff674..aec13e34c 100644--- a/browser_use/controller/registry/service.py+++ b/browser_use/controller/registry/service.py@@ -8,7 +8,6 @@ from inspect import Parameter, iscoroutinefunction, signaturefrom types import UnionTypefrom typing import Any, Generic, Optional, TypeVar, Union, get_args, get_origin-from langchain_core.language_models.chat_models import BaseChatModelfrom pydantic import BaseModel, Field, create_modelfrom browser_use.browser import BrowserSession@@ -20,6 +19,7 @@ from browser_use.controller.registry.views import (SpecialActionParameters,)from browser_use.filesystem.file_system import FileSystem+from browser_use.llm.base import BaseChatModelfrom browser_use.telemetry.service import ProductTelemetryfrom browser_use.telemetry.views import (ControllerRegisteredFunctionsTelemetryEvent,diff --git a/browser_use/controller/registry/views.py b/browser_use/controller/registry/views.pyindex fc371ff63..e80f5b576 100644--- a/browser_use/controller/registry/views.py+++ b/browser_use/controller/registry/views.py@@ -1,12 +1,12 @@from collections.abc import Callablefrom typing import TYPE_CHECKING, Any-from langchain_core.language_models.chat_models import BaseChatModelfrom pydantic import BaseModel, ConfigDictfrom browser_use.browser import BrowserSessionfrom browser_use.browser.types import Pagefrom browser_use.filesystem.file_system import FileSystem+from browser_use.llm.base import BaseChatModelif TYPE_CHECKING:pass@@ -48,7 +48,7 @@ class ActionModel(BaseModel):# click_element = param_model = ClickElementParams# done = param_model = None#- model_config = ConfigDict(arbitrary_types_allowed=True)+ model_config = ConfigDict(arbitrary_types_allowed=True, extra='forbid')def get_index(self) -> int | None:"""Get the index of the action"""diff --git a/browser_use/controller/service.py b/browser_use/controller/service.pyindex 1d20df52f..829a0baef 100644--- a/browser_use/controller/service.py+++ b/browser_use/controller/service.py@@ -6,10 +6,6 @@ import refrom collections.abc import Awaitable, Callablefrom typing import Any, Generic, TypeVar, cast-from langchain_core.language_models.chat_models import BaseChatModel-from langchain_core.prompts import PromptTemplate--# from lmnr.sdk.laminar import Laminarfrom pydantic import BaseModelfrom browser_use.agent.views import ActionModel, ActionResult@@ -32,6 +28,8 @@ from browser_use.controller.views import (SwitchTabAction,)from browser_use.filesystem.file_system import FileSystem+from browser_use.llm.base import BaseChatModel+from browser_use.llm.messages import UserMessagefrom browser_use.utils import time_execution_synclogger = logging.getLogger(__name__)@@ -201,7 +199,7 @@ class Controller(Generic[Context]):raise@self.registry.action('Go back', param_model=NoParamsAction)- async def go_back(params: NoParamsAction, browser_session: BrowserSession):+ async def go_back(_: NoParamsAction, browser_session: BrowserSession):await browser_session.go_back()msg = '🔙 Navigated back'logger.info(msg)@@ -436,11 +434,12 @@ Only use this for extracting info from a single product/article page, not for en3. Some/all of the information is not availableExplain the content of the page and that the requested information is not available in the page. Respond in JSON format.\nQuery: {query}\n Website:\n{page}"""- template = PromptTemplate(input_variables=['query', 'page'], template=prompt)try:- output = await page_extraction_llm.ainvoke(template.format(query=query, page=content))- output_text = output.content- extracted_content = f'Page Link: {page.url}\nQuery: {query}\nExtracted Content:\n{output_text}'+ formatted_prompt = prompt.format(query=query, page=content)+ response = await page_extraction_llm.ainvoke([UserMessage(content=formatted_prompt)])++ extracted_content = f'Page Link: {page.url}\nQuery: {query}\nExtracted Content:\n{response.completion}'+# if content is small include it to memoryMAX_MEMORY_SIZE = 600if len(extracted_content) < MAX_MEMORY_SIZE:@@ -661,12 +660,15 @@ Explain the content of the page and that the requested information is not availaif len(result) > MAX_MEMORY_SIZE:lines = result.splitlines()display = ''+ lines_count = 0for line in lines:if len(display) + len(line) < MAX_MEMORY_SIZE:display += line + '\n'+ lines_count += 1else:break- memory = f'{display}{len(lines) - len(display)} more lines...'+ remaining_lines = len(lines) - lines_count+ memory = f'{display}{remaining_lines} more lines...' if remaining_lines > 0 else displayelse:memory = resultlogger.info(f'💾 {memory}')diff --git a/browser_use/controller/views.py b/browser_use/controller/views.pyindex 0a46e513d..42641352e 100644--- a/browser_use/controller/views.py+++ b/browser_use/controller/views.py@@ -1,4 +1,4 @@-from pydantic import BaseModel, ConfigDict, Field, model_validator+from pydantic import BaseModel, ConfigDict, Field# Action Input Models@@ -57,12 +57,8 @@ class NoParamsAction(BaseModel):and discards it, so the final parsed model is empty."""- model_config = ConfigDict(extra='allow')-- @model_validator(mode='before')- def ignore_all_inputs(cls, values):- # No matter what the user sends, discard it and return empty.- return {}+ model_config = ConfigDict(extra='ignore')+ # No fields defined - all inputs are ignored automaticallyclass Position(BaseModel):diff --git a/browser_use/llm/__init__.py b/browser_use/llm/__init__.pynew file mode 100644index 000000000..937b63153--- /dev/null+++ b/browser_use/llm/__init__.py@@ -0,0 +1,48 @@+"""+We have switched all of our code from langchain to openai.types.chat.chat_completion_message_param.++For easier transition we have+"""++from browser_use.llm.anthropic.chat import ChatAnthropic+from browser_use.llm.azure.chat import ChatAzureOpenAI+from browser_use.llm.base import BaseChatModel+from browser_use.llm.google.chat import ChatGoogle+from browser_use.llm.groq.chat import ChatGroq+from browser_use.llm.messages import (+ AssistantMessage,+ BaseMessage,+ SystemMessage,+ UserMessage,+)+from browser_use.llm.messages import (+ ContentPartImageParam as ContentImage,+)+from browser_use.llm.messages import (+ ContentPartRefusalParam as ContentRefusal,+)+from browser_use.llm.messages import (+ ContentPartTextParam as ContentText,+)+from browser_use.llm.openai.chat import ChatOpenAI++# Make better names for the message++__all__ = [+ # Message types -> for easier transition from langchain+ 'BaseMessage',+ 'UserMessage',+ 'SystemMessage',+ 'AssistantMessage',+ # Content parts with better names+ 'ContentText',+ 'ContentRefusal',+ 'ContentImage',+ # Chat models+ 'BaseChatModel',+ 'ChatOpenAI',+ 'ChatGoogle',+ 'ChatAnthropic',+ 'ChatGroq',+ 'ChatAzureOpenAI',+]diff --git a/browser_use/llm/anthropic/chat.py b/browser_use/llm/anthropic/chat.pynew file mode 100644index 000000000..08976417b--- /dev/null+++ b/browser_use/llm/anthropic/chat.py@@ -0,0 +1,197 @@+import json+from collections.abc import Mapping+from dataclasses import dataclass+from typing import Any, TypeVar, overload++import httpx+from anthropic import (+ APIConnectionError,+ APIStatusError,+ AsyncAnthropic,+ NotGiven,+ RateLimitError,+)+from anthropic.types import Message, ToolParam+from anthropic.types.model_param import ModelParam+from anthropic.types.text_block import TextBlock+from anthropic.types.tool_choice_tool_param import ToolChoiceToolParam+from httpx import Timeout+from pydantic import BaseModel++from browser_use.llm.anthropic.serializer import AnthropicMessageSerializer+from browser_use.llm.base import BaseChatModel+from browser_use.llm.exceptions import ModelProviderError, ModelRateLimitError+from browser_use.llm.messages import BaseMessage+from browser_use.llm.views import ChatInvokeCompletion, ChatInvokeUsage++T = TypeVar('T', bound=BaseModel)+++@dataclass+class ChatAnthropic(BaseChatModel):+ """+ A wrapper around Anthropic's chat model.+ """++ # Model configuration+ model: str | ModelParam+ max_tokens: int = 8192+ temperature: float | None = None++ # Client initialization parameters+ api_key: str | None = None+ auth_token: str | None = None+ base_url: str | httpx.URL | None = None+ timeout: float | Timeout | None | NotGiven = NotGiven()+ max_retries: int = 2+ default_headers: Mapping[str, str] | None = None+ default_query: Mapping[str, object] | None = None++ # Static+ @property+ def provider(self) -> str:+ return 'anthropic'++ def _get_client_params(self) -> dict[str, Any]:+ """Prepare client parameters dictionary."""+ # Define base client params+ base_params = {+ 'api_key': self.api_key,+ 'auth_token': self.auth_token,+ 'base_url': self.base_url,+ 'timeout': self.timeout,+ 'max_retries': self.max_retries,+ 'default_headers': self.default_headers,+ 'default_query': self.default_query,+ }++ # Create client_params dict with non-None values and non-NotGiven values+ client_params = {}+ for k, v in base_params.items():+ if v is not None and v is not NotGiven():+ client_params[k] = v++ return client_params++ def _get_client_params_for_invoke(self):+ """Prepare client parameters dictionary for invoke."""++ client_params = {}++ if self.temperature is not None:+ client_params['temperature'] = self.temperature++ if self.max_tokens is not None:+ client_params['max_tokens'] = self.max_tokens++ return client_params++ def get_client(self) -> AsyncAnthropic:+ """+ Returns an AsyncAnthropic client.++ Returns:+ AsyncAnthropic: An instance of the AsyncAnthropic client.+ """+ client_params = self._get_client_params()+ return AsyncAnthropic(**client_params)++ @property+ def name(self) -> str:+ return str(self.model)++ def _get_usage(self, response: Message) -> ChatInvokeUsage | None:+ usage = ChatInvokeUsage(+ prompt_tokens=response.usage.input_tokens,+ completion_tokens=response.usage.output_tokens,+ total_tokens=response.usage.input_tokens + response.usage.output_tokens,+ )+ return usage++ @overload+ async def ainvoke(self, messages: list[BaseMessage], output_format: None = None) -> ChatInvokeCompletion[str]: ...++ @overload+ async def ainvoke(self, messages: list[BaseMessage], output_format: type[T]) -> ChatInvokeCompletion[T]: ...++ async def ainvoke(+ self, messages: list[BaseMessage], output_format: type[T] | None = None+ ) -> ChatInvokeCompletion[T] | ChatInvokeCompletion[str]:+ anthropic_messages, system_prompt = AnthropicMessageSerializer.serialize_messages(messages)++ try:+ if output_format is None:+ # Normal completion without structured output+ response = await self.get_client().messages.create(+ model=self.model, messages=anthropic_messages, **self._get_client_params_for_invoke()+ )++ usage = self._get_usage(response)++ # Extract text from the first content block+ first_content = response.content[0]+ if isinstance(first_content, TextBlock):+ response_text = first_content.text+ else:+ # If it's not a text block, convert to string+ response_text = str(first_content)++ return ChatInvokeCompletion(+ completion=response_text,+ usage=usage,+ )++ else:+ # Use tool calling for structured output+ # Create a tool that represents the output format+ tool_name = output_format.__name__+ schema = output_format.model_json_schema()++ # Remove title from schema if present (Anthropic doesn't like it in parameters)+ if 'title' in schema:+ del schema['title']++ tool = ToolParam(+ name=tool_name, description=f'Extract information in the format of {tool_name}', input_schema=schema+ )++ # Force the model to use this tool+ tool_choice = ToolChoiceToolParam(type='tool', name=tool_name)++ response = await self.get_client().messages.create(+ model=self.model,+ messages=anthropic_messages,+ tools=[tool],+ tool_choice=tool_choice,+ **self._get_client_params_for_invoke(),+ )++ usage = self._get_usage(response)++ # Extract the tool use block+ for content_block in response.content:+ if hasattr(content_block, 'type') and content_block.type == 'tool_use':+ # Parse the tool input as the structured output+ try:+ return ChatInvokeCompletion(completion=output_format.model_validate(content_block.input), usage=usage)+ except Exception as e:+ # If validation fails, try to parse it as JSON first+ if isinstance(content_block.input, str):+ data = json.loads(content_block.input)+ return ChatInvokeCompletion(+ completion=output_format.model_validate(data),+ usage=usage,+ )+ raise e++ # If no tool use block found, raise an error+ raise ValueError('Expected tool use in response but none found')++ except APIConnectionError as e:+ raise ModelProviderError(message=e.message, model=self.name) from e+ except RateLimitError as e:+ raise ModelRateLimitError(message=e.message, model=self.name) from e+ except APIStatusError as e:+ raise ModelProviderError(message=e.message, status_code=e.status_code, model=self.name) from e+ except Exception as e:+ raise ModelProviderError(message=str(e), model=self.name) from ediff --git a/browser_use/llm/anthropic/serializer.py b/browser_use/llm/anthropic/serializer.pynew file mode 100644index 000000000..b10a131cf--- /dev/null+++ b/browser_use/llm/anthropic/serializer.py@@ -0,0 +1,208 @@+from typing import overload++from anthropic.types import (+ Base64ImageSourceParam,+ ImageBlockParam,+ MessageParam,+ TextBlockParam,+ ToolUseBlockParam,+ URLImageSourceParam,+)++from browser_use.llm.messages import (+ AssistantMessage,+ BaseMessage,+ ContentPartImageParam,+ ContentPartTextParam,+ SupportedImageMediaType,+ SystemMessage,+ UserMessage,+)+++class AnthropicMessageSerializer:+ """Serializer for converting between custom message types and Anthropic message param types."""++ @staticmethod+ def _is_base64_image(url: str) -> bool:+ """Check if the URL is a base64 encoded image."""+ return url.startswith('data:image/')++ @staticmethod+ def _parse_base64_url(url: str) -> tuple[SupportedImageMediaType, str]:+ """Parse a base64 data URL to extract media type and data."""+ # Format: data:image/jpeg;base64,<data>+ if not url.startswith('data:'):+ raise ValueError(f'Invalid base64 URL: {url}')++ header, data = url.split(',', 1)+ media_type = header.split(';')[0].replace('data:', '')++ # Ensure it's a supported media type+ supported_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp']+ if media_type not in supported_types:+ # Default to jpeg if not recognized+ media_type = 'image/png'++ return media_type, data # type: ignore++ @staticmethod+ def _serialize_content_part_text(part: ContentPartTextParam) -> TextBlockParam:+ """Convert a text content part to Anthropic's TextBlockParam."""+ return TextBlockParam(text=part.text, type='text')++ @staticmethod+ def _serialize_content_part_image(part: ContentPartImageParam) -> ImageBlockParam:+ """Convert an image content part to Anthropic's ImageBlockParam."""+ url = part.image_url.url++ if AnthropicMessageSerializer._is_base64_image(url):+ # Handle base64 encoded images+ media_type, data = AnthropicMessageSerializer._parse_base64_url(url)+ return ImageBlockParam(+ source=Base64ImageSourceParam(+ data=data,+ media_type=media_type,+ type='base64',+ ),+ type='image',+ )+ else:+ # Handle URL images+ return ImageBlockParam(source=URLImageSourceParam(url=url, type='url'), type='image')++ @staticmethod+ def _serialize_content_to_str(content: str | list[ContentPartTextParam]) -> str | list[TextBlockParam]:+ """Serialize content to a string."""+ if isinstance(content, str):+ return content++ serialized_blocks: list[TextBlockParam] = []+ for part in content:+ if part.type == 'text':+ serialized_blocks.append(AnthropicMessageSerializer._serialize_content_part_text(part))++ return serialized_blocks++ @staticmethod+ def _serialize_content(+ content: str | list[ContentPartTextParam | ContentPartImageParam],+ ) -> str | list[TextBlockParam | ImageBlockParam]:+ """Serialize content to Anthropic format."""+ if isinstance(content, str):+ return content++ serialized_blocks: list[TextBlockParam | ImageBlockParam] = []+ for part in content:+ if part.type == 'text':+ serialized_blocks.append(AnthropicMessageSerializer._serialize_content_part_text(part))+ elif part.type == 'image_url':+ serialized_blocks.append(AnthropicMessageSerializer._serialize_content_part_image(part))++ return serialized_blocks++ @staticmethod+ def _serialize_tool_calls_to_content(tool_calls) -> list[ToolUseBlockParam]:+ """Convert tool calls to Anthropic's ToolUseBlockParam format."""+ blocks: list[ToolUseBlockParam] = []+ for tool_call in tool_calls:+ # Parse the arguments JSON string to object+ import json++ try:+ input_obj = json.loads(tool_call.function.arguments)+ except json.JSONDecodeError:+ # If arguments aren't valid JSON, use as string+ input_obj = {'arguments': tool_call.function.arguments}++ blocks.append(ToolUseBlockParam(id=tool_call.id, input=input_obj, name=tool_call.function.name, type='tool_use'))+ return blocks++ # region - Serialize overloads+ @overload+ @staticmethod+ def serialize(message: UserMessage) -> MessageParam: ...++ @overload+ @staticmethod+ def serialize(message: SystemMessage) -> SystemMessage: ...++ @overload+ @staticmethod+ def serialize(message: AssistantMessage) -> MessageParam: ...++ @staticmethod+ def serialize(message: BaseMessage) -> MessageParam | SystemMessage:+ """Serialize a custom message to an Anthropic MessageParam.++ Note: Anthropic doesn't have a 'system' role. System messages should be+ handled separately as the system parameter in the API call, not as a message.+ If a SystemMessage is passed here, it will be converted to a user message.+ """+ if isinstance(message, UserMessage):+ content = AnthropicMessageSerializer._serialize_content(message.content)+ return MessageParam(role='user', content=content)++ elif isinstance(message, SystemMessage):+ # Anthropic doesn't have system messages in the messages array+ # System prompts are passed separately. Convert to user message.+ return message++ elif isinstance(message, AssistantMessage):+ # Handle content and tool calls+ blocks: list[TextBlockParam | ToolUseBlockParam] = []++ # Add content blocks if present+ if message.content is not None:+ if isinstance(message.content, str):+ blocks.append(TextBlockParam(text=message.content, type='text'))+ else:+ # Process content parts (text and refusal)+ for part in message.content:+ if part.type == 'text':+ blocks.append(AnthropicMessageSerializer._serialize_content_part_text(part))+ # # Note: Anthropic doesn't have a specific refusal block type,+ # # so we convert refusals to text blocks+ # elif part.type == 'refusal':+ # blocks.append(TextBlockParam(text=f'[Refusal] {part.refusal}', type='text'))++ # Add tool use blocks if present+ if message.tool_calls:+ tool_blocks = AnthropicMessageSerializer._serialize_tool_calls_to_content(message.tool_calls)+ blocks.extend(tool_blocks)++ # If no content or tool calls, add empty text block+ # (Anthropic requires at least one content block)+ if not blocks:+ blocks.append(TextBlockParam(text='', type='text'))++ return MessageParam(+ role='assistant',+ content=blocks if len(blocks) > 1 else blocks[0].get('text', ''), # type: ignore+ )++ else:+ raise ValueError(f'Unknown message type: {type(message)}')++ @staticmethod+ def serialize_messages(messages: list[BaseMessage]) -> tuple[list[MessageParam], str | list[TextBlockParam] | None]:+ """Serialize a list of messages, extracting any system message.++ Returns:+ A tuple of (messages, system_message) where system_message is extracted+ from any SystemMessage in the list.+ """+ messages = [m.model_copy(deep=True) for m in messages]++ serialized_messages: list[MessageParam] = []+ system_message: str | list[TextBlockParam] | None = None++ for message in messages:+ result = AnthropicMessageSerializer.serialize(message)+ if isinstance(result, SystemMessage):+ # Keep the SystemMessage as-is+ system_message = AnthropicMessageSerializer._serialize_content_to_str(result.content)+ else:+ serialized_messages.append(result)++ return serialized_messages, system_messagediff --git a/browser_use/llm/azure/chat.py b/browser_use/llm/azure/chat.pynew file mode 100644index 000000000..b947a9fc8--- /dev/null+++ b/browser_use/llm/azure/chat.py@@ -0,0 +1,91 @@+import os+from dataclasses import dataclass+from typing import Any++import httpx+from openai import AsyncAzureOpenAI as AsyncAzureOpenAIClient+from openai.types.shared import ChatModel++from browser_use.llm.openai.like import ChatOpenAILike+++@dataclass+class ChatAzureOpenAI(ChatOpenAILike):+ """+ A class for to interact with any provider using the OpenAI API schema.++ Args:+ model (str): The name of the OpenAI model to use. Defaults to "not-provided".+ api_key (Optional[str]): The API key to use. Defaults to "not-provided".+ """++ # Model configuration+ model: str | ChatModel++ # Client initialization parameters+ api_key: str | None = None+ api_version: str | None = '2024-10-21'+ azure_endpoint: str | None = None+ azure_deployment: str | None = None+ base_url: str | None = None+ azure_ad_token: str | None = None+ azure_ad_token_provider: Any | None = None++ default_headers: dict[str, str] | None = None+ default_query: dict[str, Any] | None = None++ client: AsyncAzureOpenAIClient | None = None++ @property+ def provider(self) -> str:+ return 'azure'++ def _get_client_params(self) -> dict[str, Any]:+ _client_params: dict[str, Any] = {}++ self.api_key = self.api_key or os.getenv('AZURE_OPENAI_API_KEY')+ self.azure_endpoint = self.azure_endpoint or os.getenv('AZURE_OPENAI_ENDPOINT')+ self.azure_deployment = self.azure_deployment or os.getenv('AZURE_OPENAI_DEPLOYMENT')+ params_mapping = {+ 'api_key': self.api_key,+ 'api_version': self.api_version,+ 'organization': self.organization,+ 'azure_endpoint': self.azure_endpoint,+ 'azure_deployment': self.azure_deployment,+ 'base_url': self.base_url,+ 'azure_ad_token': self.azure_ad_token,+ 'azure_ad_token_provider': self.azure_ad_token_provider,+ 'http_client': self.http_client,+ }+ if self.default_headers is not None:+ _client_params['default_headers'] = self.default_headers+ if self.default_query is not None:+ _client_params['default_query'] = self.default_query++ _client_params.update({k: v for k, v in params_mapping.items() if v is not None})++ return _client_params++ def get_client(self) -> AsyncAzureOpenAIClient:+ """+ Returns an asynchronous OpenAI client.++ Returns:+ AsyncAzureOpenAIClient: An instance of the asynchronous OpenAI client.+ """+ if self.client:+ return self.client++ _client_params: dict[str, Any] = self._get_client_params()++ if self.http_client:+ _client_params['http_client'] = self.http_client+ else:+ # Create a new async HTTP client with custom limits+ _client_params['http_client'] = httpx.AsyncClient(+ limits=httpx.Limits(max_connections=1000, max_keepalive_connections=100)+ )++ self.client = AsyncAzureOpenAIClient(**_client_params)++ return self.clientdiff --git a/browser_use/llm/base.py b/browser_use/llm/base.pynew file mode 100644index 000000000..6bc4ae563--- /dev/null+++ b/browser_use/llm/base.py@@ -0,0 +1,56 @@+"""+We have switched all of our code from langchain to openai.types.chat.chat_completion_message_param.++For easier transition we have+"""++from typing import Any, Protocol, TypeVar, overload++from pydantic import BaseModel++from browser_use.llm.messages import BaseMessage+from browser_use.llm.views import ChatInvokeCompletion++T = TypeVar('T', bound=BaseModel)+++class BaseChatModel(Protocol):+ _verified_api_keys: bool = False++ model: str++ @property+ def provider(self) -> str: ...++ @property+ def name(self) -> str: ...++ @property+ def model_name(self) -> str:+ # for legacy support+ return self.model++ @overload+ async def ainvoke(self, messages: list[BaseMessage], output_format: None = None) -> ChatInvokeCompletion[str]: ...++ @overload+ async def ainvoke(self, messages: list[BaseMessage], output_format: type[T]) -> ChatInvokeCompletion[T]: ...++ async def ainvoke(+ self, messages: list[BaseMessage], output_format: type[T] | None = None+ ) -> ChatInvokeCompletion[T] | ChatInvokeCompletion[str]: ...++ @classmethod+ def __get_pydantic_core_schema__(+ cls,+ source_type: type,+ handler: Any,+ ) -> Any:+ """+ Allow this Protocol to be used in Pydantic models -> very useful to typesafe the agent settings for example.+ Returns a schema that allows any object (since this is a Protocol).+ """+ from pydantic_core import core_schema++ # Return a schema that accepts any object for Protocol types+ return core_schema.any_schema()diff --git a/browser_use/llm/exceptions.py b/browser_use/llm/exceptions.pynew file mode 100644index 000000000..aac18d7c5--- /dev/null+++ b/browser_use/llm/exceptions.py@@ -0,0 +1,27 @@+class ModelError(Exception):+ pass+++class ModelProviderError(ModelError):+ """Exception raised when a model provider returns an error."""++ def __init__(+ self,+ message: str,+ status_code: int = 502,+ model: str | None = None,+ ):+ super().__init__(message, status_code)+ self.model = model+++class ModelRateLimitError(ModelProviderError):+ """Exception raised when a model provider returns a rate limit error."""++ def __init__(+ self,+ message: str,+ status_code: int = 429,+ model: str | None = None,+ ):+ super().__init__(message, status_code, model)diff --git a/browser_use/llm/google/__init__.py b/browser_use/llm/google/__init__.pynew file mode 100644index 000000000..e4a6dde9b--- /dev/null+++ b/browser_use/llm/google/__init__.py@@ -0,0 +1,3 @@+from browser_use.llm.google.chat import ChatGoogle++__all__ = ['ChatGoogle']diff --git a/browser_use/llm/google/chat.py b/browser_use/llm/google/chat.pynew file mode 100644index 000000000..086e835b9--- /dev/null+++ b/browser_use/llm/google/chat.py@@ -0,0 +1,292 @@+import json+from dataclasses import dataclass+from typing import Any, Literal, TypeVar, overload++from google import genai+from google.auth.credentials import Credentials+from google.genai import types+from google.genai.types import MediaModality+from pydantic import BaseModel++from browser_use.llm.base import BaseChatModel+from browser_use.llm.exceptions import ModelProviderError+from browser_use.llm.google.serializer import GoogleMessageSerializer+from browser_use.llm.messages import BaseMessage+from browser_use.llm.views import ChatInvokeCompletion, ChatInvokeUsage++T = TypeVar('T', bound=BaseModel)+++VerifiedGeminiModels = Literal[+ 'gemini-2.0-flash', 'gemini-2.0-flash-exp', 'gemini-2.0-flash-lite-preview-02-05', 'Gemini-2.0-exp'+]+++@dataclass+class ChatGoogle(BaseChatModel):+ """+ A wrapper around Google's Gemini chat model using the genai client.++ This class accepts all genai.Client parameters while adding model+ and temperature parameters for the LLM interface.+ """++ # Model configuration+ model: VerifiedGeminiModels | str+ temperature: float | None = None++ # Client initialization parameters+ api_key: str | None = None+ vertexai: bool | None = None+ credentials: Credentials | None = None+ project: str | None = None+ location: str | None = None+ http_options: types.HttpOptions | types.HttpOptionsDict | None = None++ # Static+ @property+ def provider(self) -> str:+ return 'google'++ def _get_client_params(self) -> dict[str, Any]:+ """Prepare client parameters dictionary."""+ # Define base client params+ base_params = {+ 'api_key': self.api_key,+ 'vertexai': self.vertexai,+ 'credentials': self.credentials,+ 'project': self.project,+ 'location': self.location,+ 'http_options': self.http_options,+ }++ # Create client_params dict with non-None values+ client_params = {k: v for k, v in base_params.items() if v is not None}++ return client_params++ def get_client(self) -> genai.Client:+ """+ Returns a genai.Client instance.++ Returns:+ genai.Client: An instance of the Google genai client.+ """+ client_params = self._get_client_params()+ return genai.Client(**client_params)++ @property+ def name(self) -> str:+ return str(self.model)++ def _get_usage(self, response: types.GenerateContentResponse) -> ChatInvokeUsage | None:+ usage: ChatInvokeUsage | None = None++ if response.usage_metadata is not None:+ image_tokens = 0+ if response.usage_metadata.prompt_tokens_details is not None:+ image_tokens = sum(+ detail.token_count or 0+ for detail in response.usage_metadata.prompt_tokens_details+ if detail.modality == MediaModality.IMAGE+ )++ usage = ChatInvokeUsage(+ prompt_tokens=response.usage_metadata.prompt_token_count or 0,+ completion_tokens=response.usage_metadata.candidates_token_count or 0,+ total_tokens=response.usage_metadata.total_token_count or 0,+ image_tokens=image_tokens,+ )++ return usage++ @overload+ async def ainvoke(self, messages: list[BaseMessage], output_format: None = None) -> ChatInvokeCompletion[str]: ...++ @overload+ async def ainvoke(self, messages: list[BaseMessage], output_format: type[T]) -> ChatInvokeCompletion[T]: ...++ async def ainvoke(+ self, messages: list[BaseMessage], output_format: type[T] | None = None+ ) -> ChatInvokeCompletion[T] | ChatInvokeCompletion[str]:+ """+ Invoke the model with the given messages.++ Args:+ messages: List of chat messages+ output_format: Optional Pydantic model class for structured output++ Returns:+ Either a string response or an instance of output_format+ """++ # Serialize messages to Google format+ contents, system_instruction = GoogleMessageSerializer.serialize_messages(messages)++ # Return string response+ config: types.GenerateContentConfigDict = {}+ if self.temperature is not None:+ config['temperature'] = self.temperature++ # Add system instruction if present+ if system_instruction:+ config['system_instruction'] = system_instruction++ try:+ if output_format is None:+ # Return string response+ response = await self.get_client().aio.models.generate_content(+ model=self.model,+ contents=contents, # type: ignore+ config=config,+ )++ # Handle case where response.text might be None+ text = response.text or ''++ usage = self._get_usage(response)++ return ChatInvokeCompletion(+ completion=text,+ usage=usage,+ )++ else:+ # Return structured response+ config['response_mime_type'] = 'application/json'+ # Convert Pydantic model to Gemini-compatible schema+ config['response_schema'] = self._pydantic_to_gemini_schema(output_format)++ response = await self.get_client().aio.models.generate_content(+ model=self.model,+ contents=contents,+ config=config,+ )++ usage = self._get_usage(response)++ # Handle case where response.parsed might be None+ if response.parsed is None:+ # When using response_schema, Gemini returns JSON as text+ if response.text:+ try:+ # Parse the JSON text and validate with the Pydantic model+ parsed_data = json.loads(response.text)+ return ChatInvokeCompletion(+ completion=output_format.model_validate(parsed_data),+ usage=usage,+ )+ except (json.JSONDecodeError, ValueError) as e:+ raise ModelProviderError(+ message=f'Failed to parse or validate response: {str(e)}',+ status_code=500,+ model=self.model,+ ) from e+ else:+ raise ModelProviderError(+ message='No response from model',+ status_code=500,+ model=self.model,+ )++ # Ensure we return the correct type+ if isinstance(response.parsed, output_format):+ return ChatInvokeCompletion(+ completion=response.parsed,+ usage=usage,+ )+ else:+ # If it's not the expected type, try to validate it+ return ChatInvokeCompletion(+ completion=output_format.model_validate(response.parsed),+ usage=usage,+ )++ except Exception as e:+ # Handle specific Google API errors+ error_message = str(e)+ status_code: int | None = None++ # Try to extract status code if available+ if hasattr(e, 'response'):+ response_obj = getattr(e, 'response', None)+ if response_obj and hasattr(response_obj, 'status_code'):+ status_code = getattr(response_obj, 'status_code', None)++ raise ModelProviderError(+ message=error_message,+ status_code=status_code or 502, # Use default if None+ model=self.name,+ ) from e++ def _pydantic_to_gemini_schema(self, model_class: type[BaseModel]) -> dict[str, Any]:+ """+ Convert a Pydantic model to a Gemini-compatible schema.++ This function removes unsupported properties like 'additionalProperties' and resolves+ $ref references that Gemini doesn't support.+ """+ schema = model_class.model_json_schema()++ # Handle $defs and $ref resolution+ if '$defs' in schema:+ defs = schema.pop('$defs')++ def resolve_refs(obj: Any) -> Any:+ if isinstance(obj, dict):+ if '$ref' in obj:+ ref = obj.pop('$ref')+ ref_name = ref.split('/')[-1]+ if ref_name in defs:+ # Replace the reference with the actual definition+ resolved = defs[ref_name].copy()+ # Merge any additional properties from the reference+ for key, value in obj.items():+ if key != '$ref':+ resolved[key] = value+ return resolve_refs(resolved)+ return obj+ else:+ # Recursively process all dictionary values+ return {k: resolve_refs(v) for k, v in obj.items()}+ elif isinstance(obj, list):+ return [resolve_refs(item) for item in obj]+ return obj++ schema = resolve_refs(schema)++ # Remove unsupported properties+ def clean_schema(obj: Any) -> Any:+ if isinstance(obj, dict):+ # Remove unsupported properties+ cleaned = {}+ for key, value in obj.items():+ if key not in ['additionalProperties', 'title', 'default']:+ cleaned_value = clean_schema(value)+ # Handle empty object properties - Gemini doesn't allow empty OBJECT types+ if (+ key == 'properties'+ and isinstance(cleaned_value, dict)+ and len(cleaned_value) == 0+ and obj.get('type', '').upper() == 'OBJECT'+ ):+ # Convert empty object to have at least one property+ cleaned['properties'] = {'_placeholder': {'type': 'string'}}+ else:+ cleaned[key] = cleaned_value++ # If this is an object type with empty properties, add a placeholder+ if (+ cleaned.get('type', '').upper() == 'OBJECT'+ and 'properties' in cleaned+ and isinstance(cleaned['properties'], dict)+ and len(cleaned['properties']) == 0+ ):+ cleaned['properties'] = {'_placeholder': {'type': 'string'}}++ return cleaned+ elif isinstance(obj, list):+ return [clean_schema(item) for item in obj]+ return obj++ return clean_schema(schema)diff --git a/browser_use/llm/google/serializer.py b/browser_use/llm/google/serializer.pynew file mode 100644index 000000000..2edf6b107--- /dev/null+++ b/browser_use/llm/google/serializer.py@@ -0,0 +1,102 @@+import base64++from google.genai.types import Content, ContentListUnion, Part++from browser_use.llm.messages import (+ AssistantMessage,+ BaseMessage,+ SystemMessage,+ UserMessage,+)+++class GoogleMessageSerializer:+ """Serializer for converting messages to Google Gemini format."""++ @staticmethod+ def serialize_messages(messages: list[BaseMessage]) -> tuple[ContentListUnion, str | None]:+ """+ Convert a list of BaseMessages to Google format, extracting system message.++ Google handles system instructions separately from the conversation, so we need to:+ 1. Extract any system messages and return them separately as a string+ 2. Convert the remaining messages to Content objects++ Args:+ messages: List of messages to convert++ Returns:+ A tuple of (formatted_messages, system_message) where:+ - formatted_messages: List of Content objects for the conversation+ - system_message: System instruction string or None+ """++ messages = [m.model_copy(deep=True) for m in messages]++ formatted_messages: ContentListUnion = []+ system_message: str | None = None++ for message in messages:+ role = message.role if hasattr(message, 'role') else None++ # Handle system/developer messages+ if isinstance(message, SystemMessage) or role in ['system', 'developer']:+ # Extract system message content as string+ if isinstance(message.content, str):+ system_message = message.content+ elif message.content is not None:+ # Handle Iterable of content parts+ parts = []+ for part in message.content:+ if part.type == 'text':+ parts.append(part.text)+ system_message = '\n'.join(parts)+ continue++ # Determine the role for non-system messages+ if isinstance(message, UserMessage):+ role = 'user'+ elif isinstance(message, AssistantMessage):+ role = 'model'+ else:+ # Default to user for any unknown message types+ role = 'user'++ # Initialize message parts+ message_parts: list[Part] = []++ # Extract content and create parts+ if isinstance(message.content, str):+ # Regular text content+ message_parts = [Part.from_text(text=message.content)]+ elif message.content is not None:+ # Handle Iterable of content parts+ for part in message.content:+ if part.type == 'text':+ message_parts.append(Part.from_text(text=part.text))+ elif part.type == 'refusal':+ message_parts.append(Part.from_text(text=f'[Refusal] {part.refusal}'))+ elif part.type == 'image_url':+ # Handle images+ url = part.image_url.url++ # Format: data:image/png;base64,<data>+ header, data = url.split(',', 1)+ # Decode base64 to bytes+ image_bytes = base64.b64decode(data)++ # Save the image to a file+ with open('tmp/image.png', 'wb') as f:+ f.write(image_bytes)++ # Add image part+ image_part = Part.from_bytes(data=image_bytes, mime_type='image/png')++ message_parts.append(image_part)++ # Create the Content object+ if message_parts:+ final_message = Content(role=role, parts=message_parts)+ formatted_messages.append(final_message)++ return formatted_messages, system_messagediff --git a/browser_use/llm/groq/chat.py b/browser_use/llm/groq/chat.pynew file mode 100644index 000000000..57028d79f--- /dev/null+++ b/browser_use/llm/groq/chat.py@@ -0,0 +1,143 @@+from dataclasses import dataclass+from typing import Literal, TypeVar, overload++from groq import (+ DEFAULT_MAX_RETRIES,+ APIError,+ APIResponseValidationError,+ APIStatusError,+ AsyncGroq,+ NotGiven,+ RateLimitError,+ Timeout,+)+from groq.types.chat import ChatCompletion+from groq.types.chat.completion_create_params import (+ ResponseFormatResponseFormatJsonSchema,+ ResponseFormatResponseFormatJsonSchemaJsonSchema,+)+from httpx import URL+from pydantic import BaseModel++from browser_use.llm.base import BaseChatModel, ChatInvokeCompletion+from browser_use.llm.exceptions import ModelProviderError, ModelRateLimitError+from browser_use.llm.groq.serializer import GroqMessageSerializer+from browser_use.llm.messages import BaseMessage+from browser_use.llm.views import ChatInvokeUsage++GroqVerifiedModels = Literal[+ 'meta-llama/llama-4-maverick-17b-128e-instruct', 'meta-llama/llama-4-scout-17b-16e-instruct', 'qwen/qwen3-32b'+]++T = TypeVar('T', bound=BaseModel)+++@dataclass+class ChatGroq(BaseChatModel):+ """+ A wrapper around AsyncGroq that implements the BaseLLM protocol.+ """++ # Model configuration+ model: GroqVerifiedModels | str++ # Model params+ temperature: float | None = None++ # Client initialization parameters+ api_key: str | None = None+ base_url: str | URL | None = None+ timeout: float | Timeout | NotGiven | None = None+ max_retries: int = DEFAULT_MAX_RETRIES++ def get_client(self) -> AsyncGroq:+ return AsyncGroq(api_key=self.api_key, base_url=self.base_url, timeout=self.timeout, max_retries=self.max_retries)++ @property+ def provider(self) -> str:+ return 'groq'++ @property+ def name(self) -> str:+ return str(self.model)++ def _get_usage(self, response: ChatCompletion) -> ChatInvokeUsage | None:+ usage = (+ ChatInvokeUsage(+ prompt_tokens=response.usage.prompt_tokens,+ completion_tokens=response.usage.completion_tokens,+ total_tokens=response.usage.total_tokens,+ )+ if response.usage is not None+ else None+ )+ return usage++ @overload+ async def ainvoke(self, messages: list[BaseMessage], output_format: None = None) -> ChatInvokeCompletion[str]: ...++ @overload+ async def ainvoke(self, messages: list[BaseMessage], output_format: type[T]) -> ChatInvokeCompletion[T]: ...++ async def ainvoke(+ self, messages: list[BaseMessage], output_format: type[T] | None = None+ ) -> ChatInvokeCompletion[T] | ChatInvokeCompletion[str]:+ groq_messages = GroqMessageSerializer.serialize_messages(messages)++ try:+ if output_format is None:+ chat_completion = await self.get_client().chat.completions.create(+ messages=groq_messages,+ model=self.model,+ temperature=self.temperature,+ )+ usage = self._get_usage(chat_completion)+ return ChatInvokeCompletion(+ completion=chat_completion.choices[0].message.content or '',+ usage=usage,+ )++ else:+ schema = output_format.model_json_schema()+ schema['additionalProperties'] = False++ # Return structured response+ response = await self.get_client().chat.completions.create(+ model=self.model,+ messages=groq_messages,+ temperature=self.temperature,+ response_format=ResponseFormatResponseFormatJsonSchema(+ json_schema=ResponseFormatResponseFormatJsonSchemaJsonSchema(+ name=output_format.__name__,+ description='Model output schema',+ schema=schema,+ strict=True,+ ),+ type='json_schema',+ ),+ )++ if not response.choices[0].message.content:+ raise ModelProviderError(+ message='No content in response',+ status_code=500,+ model=self.name,+ )++ parsed_response = output_format.model_validate_json(response.choices[0].message.content)++ usage = self._get_usage(response)+ return ChatInvokeCompletion(+ completion=parsed_response,+ usage=usage,+ )++ except RateLimitError as e:+ raise ModelRateLimitError(message=e.response.text, status_code=e.response.status_code, model=self.name) from e++ except (APIResponseValidationError, APIStatusError) as e:+ raise ModelProviderError(message=e.response.text, status_code=e.response.status_code, model=self.name) from e+ except APIError as e:+ raise ModelProviderError(message=e.message, model=self.name) from e+ except Exception as e:+ raise ModelProviderError(message=str(e), model=self.name) from ediff --git a/browser_use/llm/groq/serializer.py b/browser_use/llm/groq/serializer.pynew file mode 100644index 000000000..f610edb4e--- /dev/null+++ b/browser_use/llm/groq/serializer.py@@ -0,0 +1,173 @@+from typing import overload++from groq.types.chat import (+ ChatCompletionAssistantMessageParam,+ ChatCompletionContentPartImageParam,+ ChatCompletionContentPartTextParam,+ ChatCompletionMessageParam,+ ChatCompletionMessageToolCallParam,+ ChatCompletionSystemMessageParam,+ ChatCompletionUserMessageParam,+)+from groq.types.chat.chat_completion_content_part_image_param import ImageURL+from groq.types.chat.chat_completion_message_tool_call_param import Function++from browser_use.llm.messages import (+ AssistantMessage,+ BaseMessage,+ ContentPartImageParam,+ ContentPartRefusalParam,+ ContentPartTextParam,+ SystemMessage,+ ToolCall,+ UserMessage,+)+++class GroqMessageSerializer:+ """Serializer for converting between custom message types and OpenAI message param types."""++ @staticmethod+ def _serialize_content_part_text(part: ContentPartTextParam) -> ChatCompletionContentPartTextParam:+ return ChatCompletionContentPartTextParam(text=part.text, type='text')++ @staticmethod+ def _serialize_content_part_image(part: ContentPartImageParam) -> ChatCompletionContentPartImageParam:+ return ChatCompletionContentPartImageParam(+ image_url=ImageURL(url=part.image_url.url, detail=part.image_url.detail),+ type='image_url',+ )++ @staticmethod+ def _serialize_user_content(+ content: str | list[ContentPartTextParam | ContentPartImageParam],+ ) -> str | list[ChatCompletionContentPartTextParam | ChatCompletionContentPartImageParam]:+ """Serialize content for user messages (text and images allowed)."""+ if isinstance(content, str):+ return content++ serialized_parts: list[ChatCompletionContentPartTextParam | ChatCompletionContentPartImageParam] = []+ for part in content:+ if part.type == 'text':+ serialized_parts.append(GroqMessageSerializer._serialize_content_part_text(part))+ elif part.type == 'image_url':+ serialized_parts.append(GroqMessageSerializer._serialize_content_part_image(part))+ return serialized_parts++ @staticmethod+ def _serialize_system_content(+ content: str | list[ContentPartTextParam],+ ) -> str:+ """Serialize content for system messages (text only)."""+ if isinstance(content, str):+ return content++ serialized_parts: list[str] = []+ for part in content:+ if part.type == 'text':+ serialized_parts.append(GroqMessageSerializer._serialize_content_part_text(part)['text'])++ return '\n'.join(serialized_parts)++ @staticmethod+ def _serialize_tool_content(+ content: str | list[ContentPartTextParam],+ ) -> str | list[ChatCompletionContentPartTextParam]:+ """Serialize content for tool messages (text only)."""+ if isinstance(content, str):+ return content++ serialized_parts: list[ChatCompletionContentPartTextParam] = []+ for part in content:+ if part.type == 'text':+ serialized_parts.append(GroqMessageSerializer._serialize_content_part_text(part))+ return serialized_parts++ @staticmethod+ def _serialize_assistant_content(+ content: str | list[ContentPartTextParam | ContentPartRefusalParam] | None,+ ) -> str | list[ChatCompletionContentPartTextParam] | None:+ """Serialize content for assistant messages (text and refusal allowed)."""+ if content is None:+ return None+ if isinstance(content, str):+ return content++ serialized_parts: list[ChatCompletionContentPartTextParam] = []+ for part in content:+ if part.type == 'text':+ serialized_parts.append(GroqMessageSerializer._serialize_content_part_text(part))++ return serialized_parts++ @staticmethod+ def _serialize_tool_call(tool_call: ToolCall) -> ChatCompletionMessageToolCallParam:+ return ChatCompletionMessageToolCallParam(+ id=tool_call.id,+ function=Function(name=tool_call.function.name, arguments=tool_call.function.arguments),+ type='function',+ )++ # endregion++ # region - Serialize overloads+ @overload+ @staticmethod+ def serialize(message: UserMessage) -> ChatCompletionUserMessageParam: ...++ @overload+ @staticmethod+ def serialize(message: SystemMessage) -> ChatCompletionSystemMessageParam: ...++ @overload+ @staticmethod+ def serialize(message: AssistantMessage) -> ChatCompletionAssistantMessageParam: ...++ @staticmethod+ def serialize(message: BaseMessage) -> ChatCompletionMessageParam:+ """Serialize a custom message to an OpenAI message param."""++ if isinstance(message, UserMessage):+ user_result: ChatCompletionUserMessageParam = {+ 'role': 'user',+ 'content': GroqMessageSerializer._serialize_user_content(message.content),+ }+ if message.name is not None:+ user_result['name'] = message.name+ return user_result++ elif isinstance(message, SystemMessage):+ system_result: ChatCompletionSystemMessageParam = {+ 'role': 'system',+ 'content': GroqMessageSerializer._serialize_system_content(message.content),+ }+ if message.name is not None:+ system_result['name'] = message.name+ return system_result++ elif isinstance(message, AssistantMessage):+ # Handle content serialization+ content = None+ if message.content is not None:+ content = GroqMessageSerializer._serialize_assistant_content(message.content)++ assistant_result: ChatCompletionAssistantMessageParam = {'role': 'assistant'}++ # Only add content if it's not None+ if content is not None:+ assistant_result['content'] = content++ if message.name is not None:+ assistant_result['name'] = message.name++ if message.tool_calls:+ assistant_result['tool_calls'] = [GroqMessageSerializer._serialize_tool_call(tc) for tc in message.tool_calls]++ return assistant_result++ else:+ raise ValueError(f'Unknown message type: {type(message)}')++ @staticmethod+ def serialize_messages(messages: list[BaseMessage]) -> list[ChatCompletionMessageParam]:+ return [GroqMessageSerializer.serialize(m) for m in messages]diff --git a/browser_use/llm/messages.py b/browser_use/llm/messages.pynew file mode 100644index 000000000..d2ca77c58--- /dev/null+++ b/browser_use/llm/messages.py@@ -0,0 +1,230 @@+"""+This implementation is based on the OpenAI types, while removing all the parts that are not needed for Browser Use.+"""++# region - Content parts+from typing import Literal, Union++from openai import BaseModel+++def _truncate(text: str, max_length: int = 50) -> str:+ """Truncate text to max_length characters, adding ellipsis if truncated."""+ if len(text) <= max_length:+ return text+ return text[: max_length - 3] + '...'+++def _format_image_url(url: str, max_length: int = 50) -> str:+ """Format image URL for display, truncating if necessary."""+ if url.startswith('data:'):+ # Base64 image+ media_type = url.split(';')[0].split(':')[1] if ';' in url else 'image'+ return f'<base64 {media_type}>'+ else:+ # Regular URL+ return _truncate(url, max_length)+++class ContentPartTextParam(BaseModel):+ text: str+ type: Literal['text'] = 'text'++ def __str__(self) -> str:+ return f'Text: {_truncate(self.text)}'++ def __repr__(self) -> str:+ return f'ContentPartTextParam(text={_truncate(self.text)})'+++class ContentPartRefusalParam(BaseModel):+ refusal: str+ type: Literal['refusal'] = 'refusal'++ def __str__(self) -> str:+ return f'Refusal: {_truncate(self.refusal)}'++ def __repr__(self) -> str:+ return f'ContentPartRefusalParam(refusal={_truncate(repr(self.refusal), 50)})'+++SupportedImageMediaType = Literal['image/jpeg', 'image/png', 'image/gif', 'image/webp']+++class ImageURL(BaseModel):+ url: str+ """Either a URL of the image or the base64 encoded image data."""+ detail: Literal['auto', 'low', 'high'] = 'auto'+ """Specifies the detail level of the image.++ Learn more in the+ [Vision guide](https://platform.openai.com/docs/guides/vision#low-or-high-fidelity-image-understanding).+ """+ # needed for Anthropic+ media_type: SupportedImageMediaType = 'image/png'++ def __str__(self) -> str:+ url_display = _format_image_url(self.url)+ return f'🖼️ Image[{self.media_type}, detail={self.detail}]: {url_display}'++ def __repr__(self) -> str:+ url_repr = _format_image_url(self.url, 30)+ return f'ImageURL(url={repr(url_repr)}, detail={repr(self.detail)}, media_type={repr(self.media_type)})'+++class ContentPartImageParam(BaseModel):+ image_url: ImageURL+ type: Literal['image_url'] = 'image_url'++ def __str__(self) -> str:+ return str(self.image_url)++ def __repr__(self) -> str:+ return f'ContentPartImageParam(image_url={repr(self.image_url)})'+++class Function(BaseModel):+ arguments: str+ """+ The arguments to call the function with, as generated by the model in JSON+ format. Note that the model does not always generate valid JSON, and may+ hallucinate parameters not defined by your function schema. Validate the+ arguments in your code before calling your function.+ """+ name: str+ """The name of the function to call."""++ def __str__(self) -> str:+ args_preview = _truncate(self.arguments, 80)+ return f'{self.name}({args_preview})'++ def __repr__(self) -> str:+ args_repr = _truncate(repr(self.arguments), 50)+ return f'Function(name={repr(self.name)}, arguments={args_repr})'+++class ToolCall(BaseModel):+ id: str+ """The ID of the tool call."""+ function: Function+ """The function that the model called."""+ type: Literal['function'] = 'function'+ """The type of the tool. Currently, only `function` is supported."""++ def __str__(self) -> str:+ return f'ToolCall[{self.id}]: {self.function}'++ def __repr__(self) -> str:+ return f'ToolCall(id={repr(self.id)}, function={repr(self.function)})'+++# endregion+++# region - Message types+++class UserMessage(BaseModel):+ role: Literal['user'] = 'user'+ """The role of the messages author, in this case `user`."""++ content: str | list[ContentPartTextParam | ContentPartImageParam]+ """The contents of the user message."""++ name: str | None = None+ """An optional name for the participant.++ Provides the model information to differentiate between participants of the same+ role.+ """++ @property+ def text(self) -> str:+ """+ Automatically parse the text inside content, whether it's a string or a list of content parts.+ """+ if isinstance(self.content, str):+ return self.content+ elif isinstance(self.content, list):+ return '\n'.join([part.text for part in self.content if part.type == 'text'])+ else:+ return ''++ def __str__(self) -> str:+ return f'UserMessage(content={self.text})'++ def __repr__(self) -> str:+ return f'UserMessage(content={repr(self.text)})'+++class SystemMessage(BaseModel):+ role: Literal['system'] = 'system'+ """The role of the messages author, in this case `system`."""++ content: str | list[ContentPartTextParam]+ """The contents of the system message."""++ name: str | None = None++ @property+ def text(self) -> str:+ """+ Automatically parse the text inside content, whether it's a string or a list of content parts.+ """+ if isinstance(self.content, str):+ return self.content+ elif isinstance(self.content, list):+ return '\n'.join([part.text for part in self.content if part.type == 'text'])+ else:+ return ''++ def __str__(self) -> str:+ return f'SystemMessage(content={self.text})'++ def __repr__(self) -> str:+ return f'SystemMessage(content={repr(self.text)})'+++class AssistantMessage(BaseModel):+ role: Literal['assistant'] = 'assistant'+ """The role of the messages author, in this case `assistant`."""++ content: str | list[ContentPartTextParam | ContentPartRefusalParam] | None+ """The contents of the assistant message."""++ name: str | None = None++ refusal: str | None = None+ """The refusal message by the assistant."""++ tool_calls: list[ToolCall] = []+ """The tool calls generated by the model, such as function calls."""++ @property+ def text(self) -> str:+ """+ Automatically parse the text inside content, whether it's a string or a list of content parts.+ """+ if isinstance(self.content, str):+ return self.content+ elif isinstance(self.content, list):+ text = ''+ for part in self.content:+ if part.type == 'text':+ text += part.text+ elif part.type == 'refusal':+ text += f'[Refusal] {part.refusal}'+ return text+ else:+ return ''++ def __str__(self) -> str:+ return f'AssistantMessage(content={self.text})'++ def __repr__(self) -> str:+ return f'AssistantMessage(content={repr(self.text)})'+++BaseMessage = Union[UserMessage, SystemMessage, AssistantMessage]++# endregiondiff --git a/browser_use/llm/openai/chat.py b/browser_use/llm/openai/chat.pynew file mode 100644index 000000000..329e65c9d--- /dev/null+++ b/browser_use/llm/openai/chat.py@@ -0,0 +1,190 @@+from collections.abc import Mapping+from dataclasses import dataclass+from typing import Any, TypeVar, overload++import httpx+from openai import APIConnectionError, APIStatusError, AsyncOpenAI, RateLimitError+from openai.types.chat.chat_completion import ChatCompletion+from openai.types.shared.chat_model import ChatModel+from pydantic import BaseModel++from browser_use.llm.base import BaseChatModel+from browser_use.llm.exceptions import ModelProviderError+from browser_use.llm.messages import BaseMessage+from browser_use.llm.openai.serializer import OpenAIMessageSerializer+from browser_use.llm.views import ChatInvokeCompletion, ChatInvokeUsage++T = TypeVar('T', bound=BaseModel)+++@dataclass+class ChatOpenAI(BaseChatModel):+ """+ A wrapper around AsyncOpenAI that implements the BaseLLM protocol.++ This class accepts all AsyncOpenAI parameters while adding model+ and temperature parameters for the LLM interface.+ """++ # Model configuration+ model: ChatModel | str++ # Model params+ temperature: float | None = None++ # Client initialization parameters+ api_key: str | None = None+ organization: str | None = None+ project: str | None = None+ base_url: str | httpx.URL | None = None+ websocket_base_url: str | httpx.URL | None = None+ timeout: float | httpx.Timeout | None = None+ max_retries: int = 2+ default_headers: Mapping[str, str] | None = None+ default_query: Mapping[str, object] | None = None+ http_client: httpx.AsyncClient | None = None+ _strict_response_validation: bool = False++ # Static+ @property+ def provider(self) -> str:+ return 'openai'++ def _get_client_params(self) -> dict[str, Any]:+ """Prepare client parameters dictionary."""+ # Define base client params+ base_params = {+ 'api_key': self.api_key,+ 'organization': self.organization,+ 'project': self.project,+ 'base_url': self.base_url,+ 'websocket_base_url': self.websocket_base_url,+ 'timeout': self.timeout,+ 'max_retries': self.max_retries,+ 'default_headers': self.default_headers,+ 'default_query': self.default_query,+ '_strict_response_validation': self._strict_response_validation,+ }++ # Create client_params dict with non-None values+ client_params = {k: v for k, v in base_params.items() if v is not None}++ # Add http_client if provided+ if self.http_client is not None:+ client_params['http_client'] = self.http_client++ return client_params++ def get_client(self) -> AsyncOpenAI:+ """+ Returns an AsyncOpenAI client.++ Returns:+ AsyncOpenAI: An instance of the AsyncOpenAI client.+ """+ client_params = self._get_client_params()+ return AsyncOpenAI(**client_params)++ @property+ def name(self) -> str:+ return str(self.model)++ def _get_usage(self, response: ChatCompletion) -> ChatInvokeUsage | None:+ usage = (+ ChatInvokeUsage(+ prompt_tokens=response.usage.prompt_tokens,+ completion_tokens=response.usage.completion_tokens,+ total_tokens=response.usage.total_tokens,+ )+ if response.usage is not None+ else None+ )+ return usage++ @overload+ async def ainvoke(self, messages: list[BaseMessage], output_format: None = None) -> ChatInvokeCompletion[str]: ...++ @overload+ async def ainvoke(self, messages: list[BaseMessage], output_format: type[T]) -> ChatInvokeCompletion[T]: ...++ async def ainvoke(+ self, messages: list[BaseMessage], output_format: type[T] | None = None+ ) -> ChatInvokeCompletion[T] | ChatInvokeCompletion[str]:+ """+ Invoke the model with the given messages.++ Args:+ messages: List of chat messages+ output_format: Optional Pydantic model class for structured output++ Returns:+ Either a string response or an instance of output_format+ """++ openai_messages = OpenAIMessageSerializer.serialize_messages(messages)++ try:+ if output_format is None:+ # Return string response+ response = await self.get_client().chat.completions.create(+ model=self.model, messages=openai_messages, temperature=self.temperature+ )++ usage = self._get_usage(response)+ return ChatInvokeCompletion(+ completion=response.choices[0].message.content or '',+ usage=usage,+ )++ else:+ # Return structured response+ response = await self.get_client().beta.chat.completions.parse(+ model=self.model,+ messages=openai_messages,+ temperature=self.temperature,+ response_format=output_format,+ )+ # The parsed response is already a Pydantic model instance+ if response.choices[0].message.parsed is None:+ raise ModelProviderError(+ message='Failed to parse structured output from model response',+ status_code=500,+ model=self.name,+ )++ usage = self._get_usage(response)+ return ChatInvokeCompletion(+ completion=response.choices[0].message.parsed,+ usage=usage,+ )++ except RateLimitError as e:+ error_message = e.response.json().get('error', {})+ error_message = (+ error_message.get('message', 'Unknown model error') if isinstance(error_message, dict) else error_message+ )+ raise ModelProviderError(+ message=error_message,+ status_code=e.response.status_code,+ model=self.name,+ ) from e++ except APIConnectionError as e:+ raise ModelProviderError(message=str(e), model=self.name) from e++ except APIStatusError as e:+ try:+ error_message = e.response.json().get('error', {})+ except Exception:+ error_message = e.response.text+ error_message = (+ error_message.get('message', 'Unknown model error') if isinstance(error_message, dict) else error_message+ )+ raise ModelProviderError(+ message=error_message,+ status_code=e.response.status_code,+ model=self.name,+ ) from e++ except Exception as e:+ raise ModelProviderError(message=str(e), model=self.name) from ediff --git a/browser_use/llm/openai/like.py b/browser_use/llm/openai/like.pynew file mode 100644index 000000000..c98c52dce--- /dev/null+++ b/browser_use/llm/openai/like.py@@ -0,0 +1,16 @@+from dataclasses import dataclass++from browser_use.llm.openai.chat import ChatOpenAI+++@dataclass+class ChatOpenAILike(ChatOpenAI):+ """+ A class for to interact with any provider using the OpenAI API schema.++ Args:+ model (str): The name of the OpenAI model to use. Defaults to "not-provided".+ api_key (Optional[str]): The API key to use. Defaults to "not-provided".+ """++ model: strdiff --git a/browser_use/llm/openai/serializer.py b/browser_use/llm/openai/serializer.pynew file mode 100644index 000000000..0d34fcfd7--- /dev/null+++ b/browser_use/llm/openai/serializer.py@@ -0,0 +1,179 @@+from typing import overload++from openai.types.chat import (+ ChatCompletionAssistantMessageParam,+ ChatCompletionContentPartImageParam,+ ChatCompletionContentPartRefusalParam,+ ChatCompletionContentPartTextParam,+ ChatCompletionMessageParam,+ ChatCompletionMessageToolCallParam,+ ChatCompletionSystemMessageParam,+ ChatCompletionUserMessageParam,+)+from openai.types.chat.chat_completion_content_part_image_param import ImageURL+from openai.types.chat.chat_completion_message_tool_call_param import Function++from browser_use.llm.messages import (+ AssistantMessage,+ BaseMessage,+ ContentPartImageParam,+ ContentPartRefusalParam,+ ContentPartTextParam,+ SystemMessage,+ ToolCall,+ UserMessage,+)+++class OpenAIMessageSerializer:+ """Serializer for converting between custom message types and OpenAI message param types."""++ @staticmethod+ def _serialize_content_part_text(part: ContentPartTextParam) -> ChatCompletionContentPartTextParam:+ return ChatCompletionContentPartTextParam(text=part.text, type='text')++ @staticmethod+ def _serialize_content_part_image(part: ContentPartImageParam) -> ChatCompletionContentPartImageParam:+ return ChatCompletionContentPartImageParam(+ image_url=ImageURL(url=part.image_url.url, detail=part.image_url.detail),+ type='image_url',+ )++ @staticmethod+ def _serialize_content_part_refusal(part: ContentPartRefusalParam) -> ChatCompletionContentPartRefusalParam:+ return ChatCompletionContentPartRefusalParam(refusal=part.refusal, type='refusal')++ @staticmethod+ def _serialize_user_content(+ content: str | list[ContentPartTextParam | ContentPartImageParam],+ ) -> str | list[ChatCompletionContentPartTextParam | ChatCompletionContentPartImageParam]:+ """Serialize content for user messages (text and images allowed)."""+ if isinstance(content, str):+ return content++ serialized_parts: list[ChatCompletionContentPartTextParam | ChatCompletionContentPartImageParam] = []+ for part in content:+ if part.type == 'text':+ serialized_parts.append(OpenAIMessageSerializer._serialize_content_part_text(part))+ elif part.type == 'image_url':+ serialized_parts.append(OpenAIMessageSerializer._serialize_content_part_image(part))+ return serialized_parts++ @staticmethod+ def _serialize_system_content(+ content: str | list[ContentPartTextParam],+ ) -> str | list[ChatCompletionContentPartTextParam]:+ """Serialize content for system messages (text only)."""+ if isinstance(content, str):+ return content++ serialized_parts: list[ChatCompletionContentPartTextParam] = []+ for part in content:+ if part.type == 'text':+ serialized_parts.append(OpenAIMessageSerializer._serialize_content_part_text(part))+ return serialized_parts++ @staticmethod+ def _serialize_tool_content(+ content: str | list[ContentPartTextParam],+ ) -> str | list[ChatCompletionContentPartTextParam]:+ """Serialize content for tool messages (text only)."""+ if isinstance(content, str):+ return content++ serialized_parts: list[ChatCompletionContentPartTextParam] = []+ for part in content:+ if part.type == 'text':+ serialized_parts.append(OpenAIMessageSerializer._serialize_content_part_text(part))+ return serialized_parts++ @staticmethod+ def _serialize_assistant_content(+ content: str | list[ContentPartTextParam | ContentPartRefusalParam] | None,+ ) -> str | list[ChatCompletionContentPartTextParam | ChatCompletionContentPartRefusalParam] | None:+ """Serialize content for assistant messages (text and refusal allowed)."""+ if content is None:+ return None+ if isinstance(content, str):+ return content++ serialized_parts: list[ChatCompletionContentPartTextParam | ChatCompletionContentPartRefusalParam] = []+ for part in content:+ if part.type == 'text':+ serialized_parts.append(OpenAIMessageSerializer._serialize_content_part_text(part))+ elif part.type == 'refusal':+ serialized_parts.append(OpenAIMessageSerializer._serialize_content_part_refusal(part))+ return serialized_parts++ @staticmethod+ def _serialize_tool_call(tool_call: ToolCall) -> ChatCompletionMessageToolCallParam:+ return ChatCompletionMessageToolCallParam(+ id=tool_call.id,+ function=Function(name=tool_call.function.name, arguments=tool_call.function.arguments),+ type='function',+ )++ # endregion++ # region - Serialize overloads+ @overload+ @staticmethod+ def serialize(message: UserMessage) -> ChatCompletionUserMessageParam: ...++ @overload+ @staticmethod+ def serialize(message: SystemMessage) -> ChatCompletionSystemMessageParam: ...++ @overload+ @staticmethod+ def serialize(message: AssistantMessage) -> ChatCompletionAssistantMessageParam: ...++ @staticmethod+ def serialize(message: BaseMessage) -> ChatCompletionMessageParam:+ """Serialize a custom message to an OpenAI message param."""++ if isinstance(message, UserMessage):+ user_result: ChatCompletionUserMessageParam = {+ 'role': 'user',+ 'content': OpenAIMessageSerializer._serialize_user_content(message.content),+ }+ if message.name is not None:+ user_result['name'] = message.name+ return user_result++ elif isinstance(message, SystemMessage):+ system_result: ChatCompletionSystemMessageParam = {+ 'role': 'system',+ 'content': OpenAIMessageSerializer._serialize_system_content(message.content),+ }+ if message.name is not None:+ system_result['name'] = message.name+ return system_result++ elif isinstance(message, AssistantMessage):+ # Handle content serialization+ content = None+ if message.content is not None:+ content = OpenAIMessageSerializer._serialize_assistant_content(message.content)++ assistant_result: ChatCompletionAssistantMessageParam = {'role': 'assistant'}++ # Only add content if it's not None+ if content is not None:+ assistant_result['content'] = content++ if message.name is not None:+ assistant_result['name'] = message.name+ if message.refusal is not None:+ assistant_result['refusal'] = message.refusal+ if message.tool_calls:+ assistant_result['tool_calls'] = [OpenAIMessageSerializer._serialize_tool_call(tc) for tc in message.tool_calls]++ return assistant_result++ else:+ raise ValueError(f'Unknown message type: {type(message)}')++ @staticmethod+ def serialize_messages(messages: list[BaseMessage]) -> list[ChatCompletionMessageParam]:+ return [OpenAIMessageSerializer.serialize(m) for m in messages]diff --git a/browser_use/llm/tests/test_chat_models.py b/browser_use/llm/tests/test_chat_models.pynew file mode 100644index 000000000..429cfcb5e--- /dev/null+++ b/browser_use/llm/tests/test_chat_models.py@@ -0,0 +1,211 @@+import os++import pytest+from pydantic import BaseModel++from browser_use.llm import ChatAnthropic, ChatGoogle, ChatGroq, ChatOpenAI+from browser_use.llm.messages import ContentPartTextParam+++class CapitalResponse(BaseModel):+ """Structured response for capital question"""++ country: str+ capital: str+++class TestChatModels:+ from browser_use.llm.messages import (+ AssistantMessage,+ BaseMessage,+ SystemMessage,+ UserMessage,+ )++ """Test suite for all chat model implementations"""++ # Test Constants+ SYSTEM_MESSAGE = SystemMessage(content=[ContentPartTextParam(text='You are a helpful assistant.', type='text')])+ FRANCE_QUESTION = UserMessage(content='What is the capital of France? Answer in one word.')+ FRANCE_ANSWER = AssistantMessage(content='Paris')+ GERMANY_QUESTION = UserMessage(content='What is the capital of Germany? Answer in one word.')++ # Expected values+ EXPECTED_GERMANY_CAPITAL = 'berlin'+ EXPECTED_FRANCE_COUNTRY = 'france'+ EXPECTED_FRANCE_CAPITAL = 'paris'++ # Test messages for conversation+ CONVERSATION_MESSAGES: list[BaseMessage] = [+ SYSTEM_MESSAGE,+ FRANCE_QUESTION,+ FRANCE_ANSWER,+ GERMANY_QUESTION,+ ]++ # Test messages for structured output+ STRUCTURED_MESSAGES: list[BaseMessage] = [UserMessage(content='What is the capital of France?')]++ # OpenAI Tests+ @pytest.mark.asyncio+ async def test_openai_ainvoke_normal(self):+ """Test normal text response from OpenAI"""+ # Skip if no API key+ if not os.getenv('OPENAI_API_KEY'):+ pytest.skip('OPENAI_API_KEY not set')++ chat = ChatOpenAI(model='gpt-4o-mini', temperature=0)+ response = await chat.ainvoke(self.CONVERSATION_MESSAGES)+ completion = response.completion++ assert isinstance(completion, str)+ assert self.EXPECTED_GERMANY_CAPITAL in completion.lower()++ @pytest.mark.asyncio+ async def test_openai_ainvoke_structured(self):+ """Test structured output from OpenAI"""+ # Skip if no API key+ if not os.getenv('OPENAI_API_KEY'):+ pytest.skip('OPENAI_API_KEY not set')++ chat = ChatOpenAI(model='gpt-4o-mini', temperature=0)+ response = await chat.ainvoke(self.STRUCTURED_MESSAGES, output_format=CapitalResponse)+ completion = response.completion++ assert isinstance(completion, CapitalResponse)+ assert completion.country.lower() == self.EXPECTED_FRANCE_COUNTRY+ assert completion.capital.lower() == self.EXPECTED_FRANCE_CAPITAL++ # Anthropic Tests+ @pytest.mark.asyncio+ async def test_anthropic_ainvoke_normal(self):+ """Test normal text response from Anthropic"""+ # Skip if no API key+ if not os.getenv('ANTHROPIC_API_KEY'):+ pytest.skip('ANTHROPIC_API_KEY not set')++ chat = ChatAnthropic(model='claude-3-5-haiku-latest', max_tokens=100, temperature=0)+ response = await chat.ainvoke(self.CONVERSATION_MESSAGES)+ completion = response.completion++ assert isinstance(completion, str)+ assert self.EXPECTED_GERMANY_CAPITAL in completion.lower()++ @pytest.mark.asyncio+ async def test_anthropic_ainvoke_structured(self):+ """Test structured output from Anthropic"""+ # Skip if no API key+ if not os.getenv('ANTHROPIC_API_KEY'):+ pytest.skip('ANTHROPIC_API_KEY not set')++ chat = ChatAnthropic(model='claude-3-5-haiku-latest', max_tokens=100, temperature=0)+ response = await chat.ainvoke(self.STRUCTURED_MESSAGES, output_format=CapitalResponse)+ completion = response.completion++ assert isinstance(completion, CapitalResponse)+ assert completion.country.lower() == self.EXPECTED_FRANCE_COUNTRY+ assert completion.capital.lower() == self.EXPECTED_FRANCE_CAPITAL++ # Google Gemini Tests+ @pytest.mark.asyncio+ async def test_google_ainvoke_normal(self):+ """Test normal text response from Google Gemini"""+ # Skip if no API key+ if not os.getenv('GOOGLE_API_KEY'):+ pytest.skip('GOOGLE_API_KEY not set')++ chat = ChatGoogle(model='gemini-2.0-flash', api_key=os.getenv('GOOGLE_API_KEY'), temperature=0)+ response = await chat.ainvoke(self.CONVERSATION_MESSAGES)+ completion = response.completion++ assert isinstance(completion, str)+ assert self.EXPECTED_GERMANY_CAPITAL in completion.lower()++ @pytest.mark.asyncio+ async def test_google_ainvoke_structured(self):+ """Test structured output from Google Gemini"""+ # Skip if no API key+ if not os.getenv('GOOGLE_API_KEY'):+ pytest.skip('GOOGLE_API_KEY not set')++ chat = ChatGoogle(model='gemini-2.0-flash', api_key=os.getenv('GOOGLE_API_KEY'), temperature=0)+ response = await chat.ainvoke(self.STRUCTURED_MESSAGES, output_format=CapitalResponse)+ completion = response.completion++ assert isinstance(completion, CapitalResponse)+ assert completion.country.lower() == self.EXPECTED_FRANCE_COUNTRY+ assert completion.capital.lower() == self.EXPECTED_FRANCE_CAPITAL++ # Google Gemini with Vertex AI Tests+ @pytest.mark.asyncio+ async def test_google_vertex_ainvoke_normal(self):+ """Test normal text response from Google Gemini via Vertex AI"""+ # Skip if no project ID+ if not os.getenv('GOOGLE_CLOUD_PROJECT'):+ pytest.skip('GOOGLE_CLOUD_PROJECT not set')++ chat = ChatGoogle(+ model='gemini-2.0-flash',+ vertexai=True,+ project=os.getenv('GOOGLE_CLOUD_PROJECT'),+ location='us-central1',+ temperature=0,+ )+ response = await chat.ainvoke(self.CONVERSATION_MESSAGES)+ completion = response.completion++ assert isinstance(completion, str)+ assert self.EXPECTED_GERMANY_CAPITAL in completion.lower()++ @pytest.mark.asyncio+ async def test_google_vertex_ainvoke_structured(self):+ """Test structured output from Google Gemini via Vertex AI"""+ # Skip if no project ID+ if not os.getenv('GOOGLE_CLOUD_PROJECT'):+ pytest.skip('GOOGLE_CLOUD_PROJECT not set')++ chat = ChatGoogle(+ model='gemini-2.0-flash',+ vertexai=True,+ project=os.getenv('GOOGLE_CLOUD_PROJECT'),+ location='us-central1',+ temperature=0,+ )+ response = await chat.ainvoke(self.STRUCTURED_MESSAGES, output_format=CapitalResponse)+ completion = response.completion++ assert isinstance(completion, CapitalResponse)+ assert completion.country.lower() == self.EXPECTED_FRANCE_COUNTRY+ assert completion.capital.lower() == self.EXPECTED_FRANCE_CAPITAL++ # Groq Tests++ @pytest.mark.asyncio+ async def test_groq_ainvoke_normal(self):+ """Test normal text response from Groq"""+ # Skip if no API key+ if not os.getenv('GROQ_API_KEY'):+ pytest.skip('GROQ_API_KEY not set')++ chat = ChatGroq(model='meta-llama/llama-4-maverick-17b-128e-instruct', temperature=0)+ response = await chat.ainvoke(self.CONVERSATION_MESSAGES)+ completion = response.completion++ assert isinstance(completion, str)+ assert self.EXPECTED_GERMANY_CAPITAL in completion.lower()++ @pytest.mark.asyncio+ async def test_groq_ainvoke_structured(self):+ """Test structured output from Groq"""+ # Skip if no API key+ if not os.getenv('GROQ_API_KEY'):+ pytest.skip('GROQ_API_KEY not set')++ chat = ChatGroq(model='meta-llama/llama-4-maverick-17b-128e-instruct', temperature=0)+ response = await chat.ainvoke(self.STRUCTURED_MESSAGES, output_format=CapitalResponse)++ completion = response.completion++ assert isinstance(completion, CapitalResponse)+ assert completion.country.lower() == self.EXPECTED_FRANCE_COUNTRY+ assert completion.capital.lower() == self.EXPECTED_FRANCE_CAPITALdiff --git a/browser_use/llm/tests/test_gemini_image.py b/browser_use/llm/tests/test_gemini_image.pynew file mode 100644index 000000000..f4f3f0330--- /dev/null+++ b/browser_use/llm/tests/test_gemini_image.py@@ -0,0 +1,98 @@+import asyncio+import base64+import io+import random++from lmnr import Laminar+from PIL import Image, ImageDraw, ImageFont++from browser_use.llm.anthropic.chat import ChatAnthropic+from browser_use.llm.google.chat import ChatGoogle+from browser_use.llm.google.serializer import GoogleMessageSerializer+from browser_use.llm.messages import (+ BaseMessage,+ ContentPartImageParam,+ ContentPartTextParam,+ ImageURL,+ SystemMessage,+ UserMessage,+)+from browser_use.llm.openai.chat import ChatOpenAI++Laminar.initialize()+++def create_random_text_image(text: str = 'hello world', width: int = 4000, height: int = 4000) -> str:+ # Create image with random background color+ bg_color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))+ image = Image.new('RGB', (width, height), bg_color)+ draw = ImageDraw.Draw(image)++ # Try to use a default font, fallback to default if not available+ try:+ font = ImageFont.truetype('arial.ttf', 24)+ except Exception:+ font = ImageFont.load_default()++ # Calculate text position to center it+ bbox = draw.textbbox((0, 0), text, font=font)+ text_width = bbox[2] - bbox[0]+ text_height = bbox[3] - bbox[1]+ x = (width - text_width) // 2+ y = (height - text_height) // 2++ # Draw text with contrasting color+ text_color = (255 - bg_color[0], 255 - bg_color[1], 255 - bg_color[2])+ draw.text((x, y), text, fill=text_color, font=font)++ # Convert to base64+ buffer = io.BytesIO()+ image.save(buffer, format='PNG')+ img_data = base64.b64encode(buffer.getvalue()).decode()++ return f'data:image/png;base64,{img_data}'+++async def test_gemini_image_vision():+ """Test Gemini's ability to see and describe images."""++ # Create the LLM+ llm = ChatGoogle(model='gemini-2.0-flash-exp')+ llm = ChatAnthropic('claude-3-5-sonnet-latest')+ llm = ChatOpenAI(model='gpt-4.1')++ # Create a random image with text+ image_data_url = create_random_text_image('Hello Gemini! Can you see this text?')++ # Create messages with image+ messages: list[BaseMessage] = [+ SystemMessage(content='You are a helpful assistant that can see and describe images.'),+ UserMessage(+ content=[+ ContentPartTextParam(text='What do you see in this image? Please describe the text and any visual elements.'),+ ContentPartImageParam(image_url=ImageURL(url=image_data_url)),+ ]+ ),+ ]++ # Serialize messages for Google format+ serializer = GoogleMessageSerializer()+ formatted_messages, system_message = serializer.serialize_messages(messages)++ print('Testing Gemini image vision...')+ print(f'System message: {system_message}')++ # Make the API call+ try:+ response = await llm.ainvoke(messages)+ print('\n=== Gemini Response ===')+ print(response.completion)+ print(response.usage)+ print('=======================')+ except Exception as e:+ print(f'Error calling Gemini: {e}')+ print(f'Error type: {type(e)}')+++if __name__ == '__main__':+ asyncio.run(test_gemini_image_vision())diff --git a/browser_use/llm/tests/test_groq_loop.py b/browser_use/llm/tests/test_groq_loop.pynew file mode 100644index 000000000..5c3c06af4--- /dev/null+++ b/browser_use/llm/tests/test_groq_loop.py@@ -0,0 +1,47 @@+import asyncio++from browser_use.llm import ContentText+from browser_use.llm.groq.chat import ChatGroq+from browser_use.llm.messages import SystemMessage, UserMessage++llm = ChatGroq(+ model='meta-llama/llama-4-maverick-17b-128e-instruct',+ temperature=0.5,+)+# llm = ChatOpenAI(model='gpt-4.1-mini')+++async def main():+ from pydantic import BaseModel++ class Output(BaseModel):+ reasoning: str+ answer: str++ message = [+ SystemMessage(content='You are a helpful assistant that can answer questions and help with tasks.'),+ UserMessage(+ content=[+ ContentText(+ text=r"Why is the sky blue? write exactly this into reasoning make sure to output ' with \ exactly like in the input : "+ ),+ ContentText(+ text="""+ The user\'s request is to find the lowest priced women\'s plus size one piece swimsuit in color black with a customer rating of at least 5 on Kohls.com. I am currently on the homepage of Kohls. The page has a search bar and various category links. To begin, I need to navigate to the women\'s section and search for swimsuits. I will start by clicking on the \\'Women\\' category link."""+ ),+ ]+ ),+ ]++ for i in range(5):+ print('-' * 50)+ print(f'start loop {i}')+ response = await llm.ainvoke(message, output_format=Output)+ completion = response.completion+ print(f'start reasoning: {completion.reasoning}')+ print(f'answer: {completion.answer}')+ print('-' * 50)+++if __name__ == '__main__':+ asyncio.run(main())diff --git a/browser_use/llm/tests/test_single_step.py b/browser_use/llm/tests/test_single_step.pynew file mode 100644index 000000000..315afe9ee--- /dev/null+++ b/browser_use/llm/tests/test_single_step.py@@ -0,0 +1,174 @@+import logging+import tempfile++import pytest++from browser_use.agent.prompts import AgentMessagePrompt+from browser_use.agent.service import Agent+from browser_use.browser.views import BrowserStateSummary, TabInfo+from browser_use.dom.views import DOMElementNode, SelectorMap+from browser_use.filesystem.file_system import FileSystem+from browser_use.llm.anthropic.chat import ChatAnthropic+from browser_use.llm.azure.chat import ChatAzureOpenAI+from browser_use.llm.base import BaseChatModel+from browser_use.llm.google.chat import ChatGoogle+from browser_use.llm.groq.chat import ChatGroq+from browser_use.llm.openai.chat import ChatOpenAI++# Set logging level to INFO for this module+logger = logging.getLogger(__name__)+logger.setLevel(logging.INFO)+++def create_mock_state_message(temp_dir: str):+ """Create a mock state message with a single clickable element."""++ # Create a mock DOM element with a single clickable button+ mock_button = DOMElementNode(+ tag_name='button',+ xpath="//button[@id='test-button']",+ attributes={'id': 'test-button'},+ children=[],+ is_visible=True,+ is_interactive=True,+ is_top_element=True,+ is_in_viewport=True,+ shadow_root=False,+ highlight_index=1, # This makes it clickable with index 1+ viewport_coordinates=None,+ page_coordinates=None,+ viewport_info=None,+ parent=None,+ )++ # Create selector map+ selector_map: SelectorMap = {1: mock_button}++ # Create mock tab info with proper integer page_id+ mock_tab = TabInfo(+ page_id=1, # Changed to integer+ url='https://example.com',+ title='Test Page',+ )++ # Create mock browser state with required selector_map+ mock_browser_state = BrowserStateSummary(+ element_tree=mock_button, # Using the actual DOM element+ selector_map=selector_map, # Added missing parameter+ url='https://example.com',+ title='Test Page',+ tabs=[mock_tab],+ screenshot='', # Empty screenshot+ pixels_above=0,+ pixels_below=0,+ )++ # Create file system using the provided temp directory+ mock_file_system = FileSystem(temp_dir)++ # Create the agent message prompt+ agent_prompt = AgentMessagePrompt(+ browser_state_summary=mock_browser_state,+ file_system=mock_file_system, # Now using actual FileSystem instance+ agent_history_description='', # Empty history+ read_state_description='', # Empty read state+ task='Click the button on the page',+ include_attributes=['id'],+ step_info=None,+ page_filtered_actions=None,+ max_clickable_elements_length=40000,+ sensitive_data=None,+ )++ # Override the clickable_elements_to_string method to return our simple element+ mock_button.clickable_elements_to_string = lambda include_attributes=None: '[1]<button id="test-button">Click Me</button>'++ # Get the formatted message+ message = agent_prompt.get_user_message(use_vision=False)++ return message+++# Pytest parameterized version+ 'llm_class,model_name',+ [+ (ChatGroq, 'meta-llama/llama-4-maverick-17b-128e-instruct'),+ (ChatGoogle, 'gemini-2.0-flash-exp'),+ (ChatOpenAI, 'gpt-4o-mini'),+ (ChatAnthropic, 'claude-3-5-sonnet-latest'),+ (ChatAzureOpenAI, 'gpt-4o-mini'),+ ],+)+async def test_single_step_parametrized(llm_class, model_name):+ """Test single step with different LLM providers using pytest parametrize."""+ llm = llm_class(model=model_name)++ agent = Agent(task='Click the button on the page', llm=llm)++ # Create temporary directory that will stay alive during the test+ with tempfile.TemporaryDirectory() as temp_dir:+ # Create mock state message+ mock_message = create_mock_state_message(temp_dir)++ agent.message_manager._add_message_with_type(mock_message)++ messages = agent.message_manager.get_messages()++ # Test with simple question+ response = await llm.ainvoke(messages, agent.AgentOutput)++ # Basic assertions to ensure response is valid+ assert response.completion is not None+ assert response.usage is not None+ assert response.usage.total_tokens > 0+++async def test_single_step():+ """Original test function that tests all models in a loop."""+ # Create a list of models to test+ models: list[BaseChatModel] = [+ ChatGroq(model='meta-llama/llama-4-maverick-17b-128e-instruct'),+ ChatGoogle(model='gemini-2.0-flash-exp'),+ ChatOpenAI(model='gpt-4.1'),+ ChatAnthropic(model='claude-3-5-sonnet-latest'), # Using haiku for cost efficiency+ ChatAzureOpenAI(model='gpt-4o-mini'),+ ]++ for llm in models:+ print(f'\n{"=" * 60}')+ print(f'Testing with model: {llm.provider} - {llm.model}')+ print(f'{"=" * 60}\n')++ agent = Agent(task='Click the button on the page', llm=llm)++ # Create temporary directory that will stay alive during the test+ with tempfile.TemporaryDirectory() as temp_dir:+ # Create mock state message+ mock_message = create_mock_state_message(temp_dir)++ # Print the mock message content to see what it looks like+ print('Mock state message:')+ print(mock_message.content)+ print('\n' + '=' * 50 + '\n')++ agent.message_manager._add_message_with_type(mock_message)++ messages = agent.message_manager.get_messages()++ # Test with simple question+ try:+ response = await llm.ainvoke(messages, agent.AgentOutput)+ logger.info(f'Response from {llm.provider}: {response.completion}')+ logger.info(f'Actions: {str(response.completion.action)}')++ except Exception as e:+ logger.error(f'Error with {llm.provider}: {type(e).__name__}: {str(e)}')++ print(f'\n{"=" * 60}\n')+++if __name__ == '__main__':+ import asyncio++ asyncio.run(test_single_step())diff --git a/browser_use/llm/views.py b/browser_use/llm/views.pynew file mode 100644index 000000000..c093aea91--- /dev/null+++ b/browser_use/llm/views.py@@ -0,0 +1,39 @@+from typing import TypeVar++from pydantic import BaseModel++T = TypeVar('T', bound=BaseModel)+++class ChatInvokeUsage(BaseModel):+ """+ Usage information for a chat model invocation.+ """++ prompt_tokens: int+ """The number of tokens in the prompt."""++ completion_tokens: int+ """The number of tokens in the completion."""++ total_tokens: int+ """The total number of tokens in the response."""++ image_tokens: int | None = None+ """The number of tokens in the image. Google only (prompt tokens is the text tokens + image tokens in that case)"""+++class ChatInvokeCompletion[T: BaseModel | str](BaseModel):+ """+ Response from a chat model invocation.+ """++ completion: T+ """The completion of the response."""++ # Thinking stuff+ thinking: str | None = None+ redacted_thinking: str | None = None++ usage: ChatInvokeUsage | None+ """The usage of the response."""diff --git a/browser_use/logging_config.py b/browser_use/logging_config.pyindex 1d2f1c5a8..41899ea6f 100644--- a/browser_use/logging_config.py+++ b/browser_use/logging_config.py@@ -119,7 +119,6 @@ def setup_logging():'playwright','urllib3','asyncio',- 'langchain','langsmith','langsmith.client','openai',diff --git a/browser_use/telemetry/service.py b/browser_use/telemetry/service.pyindex 234217464..d703e49c1 100644--- a/browser_use/telemetry/service.py+++ b/browser_use/telemetry/service.py@@ -6,11 +6,12 @@ from dotenv import load_dotenvfrom posthog import Posthogfrom uuid_extensions import uuid7str+from browser_use.telemetry.views import BaseTelemetryEvent+from browser_use.utils import singleton+load_dotenv()from browser_use.config import CONFIG-from browser_use.telemetry.views import BaseTelemetryEvent-from browser_use.utils import singletonlogger = logging.getLogger(__name__)diff --git a/browser_use/tokens/__init__.py b/browser_use/tokens/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/browser_use/tokens/service.py b/browser_use/tokens/service.pynew file mode 100644index 000000000..af719d482--- /dev/null+++ b/browser_use/tokens/service.py@@ -0,0 +1,480 @@+"""+Token cost service that tracks LLM token usage and costs.++Fetches pricing data from LiteLLM repository and caches it for 1 day.+Automatically tracks token usage when LLMs are registered and invoked.+"""++import asyncio+import logging+import os+from datetime import datetime, timedelta+from pathlib import Path+from typing import Any++import aiofiles+import aiofiles.os+import httpx+from dotenv import load_dotenv++from browser_use.llm.base import BaseChatModel+from browser_use.llm.views import ChatInvokeUsage+from browser_use.tokens.views import CachedPricingData, ModelPricing, ModelUsageStats, TokenUsageEntry, UsageSummary++load_dotenv()++from browser_use.config import CONFIG++logger = logging.getLogger(__name__)+cost_logger = logging.getLogger('cost')+++def xdg_cache_home() -> Path:+ default = Path.home() / '.cache'+ if CONFIG.XDG_CACHE_HOME and (path := Path(CONFIG.XDG_CACHE_HOME)).is_absolute():+ return path+ return default+++class TokenCost:+ """Service for tracking token usage and calculating costs"""++ CACHE_DIR_NAME = 'browser_use/token_cost'+ CACHE_DURATION = timedelta(days=1)+ PRICING_URL = 'https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json'++ def __init__(self, include_cost: bool = False):+ self.include_cost = include_cost or os.getenv('BROWSER_USE_CALCULATE_COST', 'false').lower() == 'true'++ self.usage_history: list[TokenUsageEntry] = []+ self.registered_llms: dict[str, BaseChatModel] = {}+ self._pricing_data: dict[str, Any] | None = None+ self._initialized = False+ self._cache_dir = xdg_cache_home() / self.CACHE_DIR_NAME++ async def initialize(self) -> None:+ """Initialize the service by loading pricing data"""+ if not self._initialized:+ if self.include_cost:+ await self._load_pricing_data()+ self._initialized = True++ async def _load_pricing_data(self) -> None:+ """Load pricing data from cache or fetch from GitHub"""+ # Try to find a valid cache file+ cache_file = await self._find_valid_cache()++ if cache_file:+ await self._load_from_cache(cache_file)+ else:+ await self._fetch_and_cache_pricing_data()++ async def _find_valid_cache(self) -> Path | None:+ """Find the most recent valid cache file"""+ try:+ # Ensure cache directory exists+ self._cache_dir.mkdir(parents=True, exist_ok=True)++ # List all JSON files in the cache directory+ cache_files = list(self._cache_dir.glob('*.json'))++ if not cache_files:+ return None++ # Sort by modification time (most recent first)+ cache_files.sort(key=lambda f: f.stat().st_mtime, reverse=True)++ # Check each file until we find a valid one+ for cache_file in cache_files:+ if await self._is_cache_valid(cache_file):+ return cache_file+ else:+ # Clean up old cache files+ try:+ os.remove(cache_file)+ except Exception:+ pass++ return None+ except Exception:+ return None++ async def _is_cache_valid(self, cache_file: Path) -> bool:+ """Check if a specific cache file is valid and not expired"""+ try:+ if not cache_file.exists():+ return False++ # Read the cached data+ async with aiofiles.open(cache_file, 'r') as f:+ content = await f.read()+ cached = CachedPricingData.model_validate_json(content)++ # Check if cache is still valid+ return datetime.now() - cached.timestamp < self.CACHE_DURATION+ except Exception:+ return False++ async def _load_from_cache(self, cache_file: Path) -> None:+ """Load pricing data from a specific cache file"""+ try:+ async with aiofiles.open(cache_file, 'r') as f:+ content = await f.read()+ cached = CachedPricingData.model_validate_json(content)+ self._pricing_data = cached.data+ except Exception as e:+ print(f'Error loading cached pricing data from {cache_file}: {e}')+ # Fall back to fetching+ await self._fetch_and_cache_pricing_data()++ async def _fetch_and_cache_pricing_data(self) -> None:+ """Fetch pricing data from LiteLLM GitHub and cache it with timestamp"""+ try:+ async with httpx.AsyncClient() as client:+ response = await client.get(self.PRICING_URL, timeout=30)+ response.raise_for_status()++ self._pricing_data = response.json()++ # Create cache object with timestamp+ cached = CachedPricingData(timestamp=datetime.now(), data=self._pricing_data or {})++ # Ensure cache directory exists+ self._cache_dir.mkdir(parents=True, exist_ok=True)++ # Create cache file with timestamp in filename+ timestamp_str = datetime.now().strftime('%Y%m%d_%H%M%S')+ cache_file = self._cache_dir / f'pricing_{timestamp_str}.json'++ async with aiofiles.open(cache_file, 'w') as f:+ await f.write(cached.model_dump_json(indent=2))++ except Exception as e:+ print(f'Error fetching pricing data: {e}')+ # Fall back to empty pricing data+ self._pricing_data = {}++ async def get_model_pricing(self, model_name: str) -> ModelPricing | None:+ """Get pricing information for a specific model"""+ # Ensure we're initialized+ if not self._initialized:+ await self.initialize()++ if not self._pricing_data or model_name not in self._pricing_data:+ return None++ data = self._pricing_data[model_name]+ return ModelPricing(+ model=model_name,+ input_cost_per_token=data.get('input_cost_per_token'),+ output_cost_per_token=data.get('output_cost_per_token'),+ max_tokens=data.get('max_tokens'),+ max_input_tokens=data.get('max_input_tokens'),+ max_output_tokens=data.get('max_output_tokens'),+ )++ def calculate_cost(self, model: str, prompt_tokens: int, completion_tokens: int) -> tuple[float, float]:+ """Calculate cost for given token counts. Returns 0 if pricing data is not available or cost tracking is disabled."""+ if not self.include_cost or not self._pricing_data or model not in self._pricing_data:+ return 0.0, 0.0++ data = self._pricing_data[model]+ input_cost_per_token = data.get('input_cost_per_token', 0.0)+ output_cost_per_token = data.get('output_cost_per_token', 0.0)++ input_cost = prompt_tokens * input_cost_per_token+ output_cost = completion_tokens * output_cost_per_token++ return input_cost, output_cost++ def add_usage(self, model: str, usage: ChatInvokeUsage) -> TokenUsageEntry:+ """Add token usage entry to history (without calculating cost)"""+ entry = TokenUsageEntry(+ model=model,+ timestamp=datetime.now(),+ prompt_tokens=usage.prompt_tokens,+ completion_tokens=usage.completion_tokens,+ total_tokens=usage.total_tokens,+ image_tokens=usage.image_tokens,+ )++ self.usage_history.append(entry)++ return entry++ async def _log_usage(self, model: str, usage: TokenUsageEntry) -> None:+ """Log usage to the logger"""+ if not self._initialized:+ await self.initialize()++ # ANSI color codes+ C_CYAN = '\033[96m'+ C_YELLOW = '\033[93m'+ C_GREEN = '\033[92m'+ C_RESET = '\033[0m'++ # Format tokens with k notation+ prompt_tokens_fmt = self._format_tokens(usage.prompt_tokens)+ completion_tokens_fmt = self._format_tokens(usage.completion_tokens)++ # Format tokens with or without cost based on whether cost tracking is enabled+ if self.include_cost:+ input_cost, output_cost = self.calculate_cost(model, usage.prompt_tokens, usage.completion_tokens)+ cost = input_cost + output_cost++ if cost > 0:+ input_part = f'{C_YELLOW}{prompt_tokens_fmt} (${input_cost:.4f}){C_RESET}'+ output_part = f'{C_GREEN}{completion_tokens_fmt} (${output_cost:.4f}){C_RESET}'+ else:+ input_part = f'{C_YELLOW}{prompt_tokens_fmt}{C_RESET}'+ output_part = f'{C_GREEN}{completion_tokens_fmt}{C_RESET}'+ else:+ input_part = f'{C_YELLOW}{prompt_tokens_fmt}{C_RESET}'+ output_part = f'{C_GREEN}{completion_tokens_fmt}{C_RESET}'++ cost_logger.info(f'🧠 llm : {C_CYAN}{model}{C_RESET} | ⬅️ tokens: {input_part} | ➡️ tokens: {output_part}')++ def register_llm(self, llm: BaseChatModel) -> BaseChatModel:+ """+ Register an LLM to automatically track its token usage++ @dev Guarantees that the same instance is not registered multiple times+ """+ # Use instance ID as key to avoid collisions between multiple instances+ instance_id = str(id(llm))++ # Check if this exact instance is already registered+ if instance_id in self.registered_llms:+ logger.debug(f'LLM instance {instance_id} ({llm.provider}_{llm.model}) is already registered')+ return llm++ self.registered_llms[instance_id] = llm++ # Store the original method+ original_ainvoke = llm.ainvoke+ # Store reference to self for use in the closure+ token_cost_service = self++ # Create a wrapped version that tracks usage+ async def tracked_ainvoke(messages, output_format=None):+ # Call the original method+ result = await original_ainvoke(messages, output_format)++ # Track usage if available (no await needed since add_usage is now sync)+ if result.usage:+ usage = token_cost_service.add_usage(llm.model, result.usage)++ logger.debug(f'Token cost service: {usage}')++ asyncio.create_task(token_cost_service._log_usage(llm.model, usage))++ return result++ # Replace the method with our tracked version+ # Using setattr to avoid type checking issues with overloaded methods+ setattr(llm, 'ainvoke', tracked_ainvoke)++ return llm++ def get_usage_summary(+ self, model: str | None = None, since: datetime | None = None, calculate_cost: bool = True+ ) -> UsageSummary:+ """Get summary of token usage and costs (costs calculated on-the-fly)"""+ filtered_usage = self.usage_history++ if model:+ filtered_usage = [u for u in filtered_usage if u.model == model]++ if since:+ filtered_usage = [u for u in filtered_usage if u.timestamp >= since]++ if not filtered_usage:+ return UsageSummary(+ total_prompt_tokens=0,+ total_prompt_cost=0.0,+ total_completion_tokens=0,+ total_completion_cost=0.0,+ total_tokens=0,+ total_cost=0.0,+ entry_count=0,+ )++ # Calculate totals+ total_prompt = sum(u.prompt_tokens for u in filtered_usage)+ total_completion = sum(u.completion_tokens for u in filtered_usage)+ total_tokens = sum(u.total_tokens for u in filtered_usage)+ models = list({u.model for u in filtered_usage})++ # Calculate per-model stats with on-the-fly cost calculation+ model_stats: dict[str, ModelUsageStats] = {}+ total_prompt_cost = 0.0+ total_completion_cost = 0.0++ for entry in filtered_usage:+ if entry.model not in model_stats:+ model_stats[entry.model] = ModelUsageStats(model=entry.model)++ stats = model_stats[entry.model]+ stats.prompt_tokens += entry.prompt_tokens+ stats.completion_tokens += entry.completion_tokens+ stats.total_tokens += entry.total_tokens+ stats.invocations += 1++ if calculate_cost:+ # Calculate cost on-the-fly+ input_cost, output_cost = self.calculate_cost(entry.model, entry.prompt_tokens, entry.completion_tokens)+ total_prompt_cost += input_cost+ total_completion_cost += output_cost++ # Calculate averages+ for stats in model_stats.values():+ if stats.invocations > 0:+ stats.average_tokens_per_invocation = stats.total_tokens / stats.invocations++ return UsageSummary(+ total_prompt_tokens=total_prompt,+ total_prompt_cost=total_prompt_cost,+ total_completion_tokens=total_completion,+ total_completion_cost=total_completion_cost,+ total_tokens=total_tokens,+ total_cost=total_prompt_cost + total_completion_cost,+ entry_count=len(filtered_usage),+ models=models,+ by_model=model_stats,+ )++ def _format_tokens(self, tokens: int) -> str:+ """Format token count with k suffix for thousands"""+ if tokens >= 1000:+ return f'{tokens / 1000:.1f}k'+ if tokens >= 1000000:+ return f'{tokens / 1000000:.1f}M'+ if tokens >= 1000000000:+ return f'{tokens / 1000000000:.1f}B'+ return str(tokens)++ async def log_usage_summary(self) -> None:+ """Log a comprehensive usage summary per model with colors and nice formatting"""+ if not self.usage_history:+ return++ summary = self.get_usage_summary(calculate_cost=self.include_cost)++ if summary.entry_count == 0:+ return++ # ANSI color codes+ C_CYAN = '\033[96m'+ C_YELLOW = '\033[93m'+ C_GREEN = '\033[92m'+ C_BLUE = '\033[94m'+ C_MAGENTA = '\033[95m'+ C_RESET = '\033[0m'+ C_BOLD = '\033[1m'++ # Log overall summary+ total_tokens_fmt = self._format_tokens(summary.total_tokens)+ prompt_tokens_fmt = self._format_tokens(summary.total_prompt_tokens)+ completion_tokens_fmt = self._format_tokens(summary.total_completion_tokens)++ # Format cost breakdowns for input and output (only if cost tracking is enabled)+ if self.include_cost and summary.total_cost > 0:+ total_cost_part = f' (${C_MAGENTA}{summary.total_cost:.4f}{C_RESET})'+ prompt_cost_part = f' (${summary.total_prompt_cost:.4f})'+ completion_cost_part = f' (${summary.total_completion_cost:.4f})'+ else:+ total_cost_part = ''+ prompt_cost_part = ''+ completion_cost_part = ''++ if len(summary.by_model) > 1:+ cost_logger.info(+ f'💲 {C_BOLD}Total Usage Summary{C_RESET}: {C_BLUE}{total_tokens_fmt} tokens{C_RESET}{total_cost_part} | '+ f'⬅️ {C_YELLOW}{prompt_tokens_fmt}{prompt_cost_part}{C_RESET} | ➡️ {C_GREEN}{completion_tokens_fmt}{completion_cost_part}{C_RESET}'+ )++ # Log per-model breakdown+ cost_logger.info(f'📊 {C_BOLD}Per-Model Usage Breakdown{C_RESET}:')++ for model, stats in summary.by_model.items():+ # Format tokens+ model_total_fmt = self._format_tokens(stats.total_tokens)+ model_prompt_fmt = self._format_tokens(stats.prompt_tokens)+ model_completion_fmt = self._format_tokens(stats.completion_tokens)+ avg_tokens_fmt = self._format_tokens(int(stats.average_tokens_per_invocation))++ # Format cost display (only if cost tracking is enabled)+ if self.include_cost:+ # Calculate per-model costs on-the-fly+ total_model_cost = 0.0+ model_prompt_cost = 0.0+ model_completion_cost = 0.0++ # Calculate costs for this model+ for entry in self.usage_history:+ if entry.model == model:+ input_cost, output_cost = self.calculate_cost(entry.model, entry.prompt_tokens, entry.completion_tokens)+ model_prompt_cost += input_cost+ model_completion_cost += output_cost++ total_model_cost = model_prompt_cost + model_completion_cost++ if total_model_cost > 0:+ cost_part = f' (${C_MAGENTA}{total_model_cost:.4f}{C_RESET})'+ prompt_part = f'{C_YELLOW}{model_prompt_fmt} (${model_prompt_cost:.4f}){C_RESET}'+ completion_part = f'{C_GREEN}{model_completion_fmt} (${model_completion_cost:.4f}){C_RESET}'+ else:+ cost_part = ''+ prompt_part = f'{C_YELLOW}{model_prompt_fmt}{C_RESET}'+ completion_part = f'{C_GREEN}{model_completion_fmt}{C_RESET}'+ else:+ cost_part = ''+ prompt_part = f'{C_YELLOW}{model_prompt_fmt}{C_RESET}'+ completion_part = f'{C_GREEN}{model_completion_fmt}{C_RESET}'++ cost_logger.info(+ f' 🤖 {C_CYAN}{model}{C_RESET}: {C_BLUE}{model_total_fmt} tokens{C_RESET}{cost_part} | '+ f'⬅️ {prompt_part} | ➡️ {completion_part} | '+ f'📞 {stats.invocations} calls | 📈 {avg_tokens_fmt}/call'+ )++ def get_cost_by_model(self) -> dict[str, ModelUsageStats]:+ """Get cost breakdown by model"""+ summary = self.get_usage_summary(calculate_cost=self.include_cost)+ return summary.by_model++ def clear_history(self) -> None:+ """Clear usage history"""+ self.usage_history = []++ async def refresh_pricing_data(self) -> None:+ """Force refresh of pricing data from GitHub"""+ if self.include_cost:+ await self._fetch_and_cache_pricing_data()++ async def clean_old_caches(self, keep_count: int = 3) -> None:+ """Clean up old cache files, keeping only the most recent ones"""+ try:+ # List all JSON files in the cache directory+ cache_files = list(self._cache_dir.glob('*.json'))++ if len(cache_files) <= keep_count:+ return++ # Sort by modification time (oldest first)+ cache_files.sort(key=lambda f: f.stat().st_mtime)++ # Remove all but the most recent files+ for cache_file in cache_files[:-keep_count]:+ try:+ os.remove(cache_file)+ except Exception:+ pass+ except Exception as e:+ print(f'Error cleaning old cache files: {e}')++ async def ensure_pricing_loaded(self) -> None:+ """Ensure pricing data is loaded in the background. Call this after creating the service."""+ if not self._initialized and self.include_cost:+ # This will run in the background and won't block+ await self.initialize()diff --git a/browser_use/tokens/tests/test_cost.py b/browser_use/tokens/tests/test_cost.pynew file mode 100644index 000000000..d88fd789a--- /dev/null+++ b/browser_use/tokens/tests/test_cost.py@@ -0,0 +1,91 @@+"""+Simple test for token cost tracking with real LLM calls.++Tests ChatOpenAI and ChatGoogle by iteratively generating countries.+"""++import asyncio+import logging++from browser_use.llm import ChatOpenAI+from browser_use.llm.messages import AssistantMessage, SystemMessage, UserMessage+from browser_use.tokens.service import TokenCost++logger = logging.getLogger(__name__)+logger.setLevel(logging.INFO)+++async def test_iterative_country_generation():+ """Test token cost tracking with iterative country generation"""++ # Initialize token cost service+ tc = TokenCost()++ # System prompt that explains the iterative task+ system_prompt = """You are a country name generator. When asked, you will provide exactly ONE country name and nothing else.+Each time you're asked to continue, provide the next country name that hasn't been mentioned yet.+Keep track of which countries you've already said and don't repeat them.+Only output the country name, no numbers, no punctuation, just the name."""++ # Test with different models+ models = [+ ChatOpenAI(model='gpt-4.1'),+ # ChatGoogle(model='gemini-2.0-flash-exp'),+ ]++ print('\n🌍 Iterative Country Generation Test')+ print('=' * 80)++ for llm in models:+ print(f'\n📍 Testing {llm.model}')+ print('-' * 60)++ # Register the LLM for automatic tracking+ tc.register_llm(llm)++ # Initialize conversation+ messages = [SystemMessage(content=system_prompt), UserMessage(content='Give me a country name')]++ countries = []++ # Generate 10 countries iteratively+ for i in range(10):+ # Call the LLM+ result = await llm.ainvoke(messages)+ country = result.completion.strip()+ countries.append(country)++ # Add the response to messages+ messages.append(AssistantMessage(content=country))++ # Add the next request (except for the last iteration)+ if i < 9:+ messages.append(UserMessage(content='Next country please'))++ print(f' Country {i + 1}: {country}')++ print(f'\n Generated countries: {", ".join(countries)}')++ # Display cost summary+ print('\n💰 Cost Summary')+ print('=' * 80)++ summary = tc.get_usage_summary()+ print(f'Total calls: {summary.entry_count}')+ print(f'Total tokens: {summary.total_tokens:,}')+ print(f'Total cost: ${summary.total_cost:.6f}')++ print('\n📊 Cost breakdown by model:')+ for model, stats in summary.by_model.items():+ print(f'\n{model}:')+ print(f' Calls: {stats.invocations}')+ print(f' Prompt tokens: {stats.prompt_tokens:,}')+ print(f' Completion tokens: {stats.completion_tokens:,}')+ print(f' Total tokens: {stats.total_tokens:,}')+ print(f' Cost: ${stats.cost:.6f}')+ print(f' Average tokens per call: {stats.average_tokens_per_invocation:.1f}')+++if __name__ == '__main__':+ # Run the test+ asyncio.run(test_iterative_country_generation())diff --git a/browser_use/tokens/views.py b/browser_use/tokens/views.pynew file mode 100644index 000000000..16bf8569c--- /dev/null+++ b/browser_use/tokens/views.py@@ -0,0 +1,61 @@+from datetime import datetime+from typing import Any, TypeVar++from pydantic import BaseModel, Field++T = TypeVar('T', bound=BaseModel)+++class TokenUsageEntry(BaseModel):+ """Single token usage entry"""++ model: str+ timestamp: datetime+ prompt_tokens: int+ completion_tokens: int+ total_tokens: int+ image_tokens: int | None = None+++class ModelPricing(BaseModel):+ """Pricing information for a model"""++ model: str+ input_cost_per_token: float | None = None+ output_cost_per_token: float | None = None+ max_tokens: int | None = None+ max_input_tokens: int | None = None+ max_output_tokens: int | None = None+++class CachedPricingData(BaseModel):+ """Cached pricing data with timestamp"""++ timestamp: datetime+ data: dict[str, Any]+++class ModelUsageStats(BaseModel):+ """Usage statistics for a single model"""++ model: str+ prompt_tokens: int = 0+ completion_tokens: int = 0+ total_tokens: int = 0+ cost: float = 0.0+ invocations: int = 0+ average_tokens_per_invocation: float = 0.0+++class UsageSummary(BaseModel):+ """Summary of token usage and costs"""++ total_prompt_tokens: int+ total_prompt_cost: float+ total_completion_tokens: int+ total_completion_cost: float+ total_tokens: int+ total_cost: float+ entry_count: int+ models: list[str] = Field(default_factory=list)+ by_model: dict[str, ModelUsageStats] = Field(default_factory=dict)diff --git a/browser_use/utils.py b/browser_use/utils.pyindex fe91a7555..fadbd557c 100644--- a/browser_use/utils.py+++ b/browser_use/utils.py@@ -529,66 +529,6 @@ def merge_dicts(a: dict, b: dict, path: tuple[str, ...] = ()):return a-class LLMException(Exception):- """Custom exception for LLM-related errors."""-- def __init__(self, code: int, message: str):- self.code = code- self.message = message- super().__init__(message)---def handle_llm_error(e: Exception) -> tuple[dict[str, Any], Any | None]:- """- Handle LLM API errors and extract failed generation data when available.-- Args:- e: The exception that occurred during LLM API call-- Returns:- Tuple containing:- - response: Dict with 'raw' and 'parsed' keys- - parsed: Parsed data (None if extraction was needed)-- Raises:- LLMException: If the error is not a recognized type with failed generation data- """- # Handle OpenAI BadRequestError with failed_generation- if (- OpenAIBadRequestError- and isinstance(e, OpenAIBadRequestError)- and hasattr(e, 'body')- and e.body # type: ignore[attr-defined]- and 'failed_generation' in e.body # type: ignore[operator]- ):- raw = e.body['failed_generation'] # type: ignore[index]- response = {'raw': raw, 'parsed': None}- parsed = None- logger.debug(f'Failed to do tool call, trying to parse raw response: {raw}')- return response, parsed-- # Handle Groq BadRequestError with failed_generation- if (- GroqBadRequestError is not None- and isinstance(e, GroqBadRequestError)- and hasattr(e, 'body')- and e.body # type: ignore[attr-defined]- and isinstance(e.body, dict) # type: ignore[attr-defined]- and 'error' in e.body # type: ignore[attr-defined]- and isinstance(e.body['error'], dict) # type: ignore[attr-defined,index]- and 'failed_generation' in e.body['error'] # type: ignore[attr-defined,index]- ):- raw = e.body['error']['failed_generation'] # type: ignore[attr-defined,index]- response = {'raw': raw, 'parsed': None}- parsed = None- logger.debug(f'Failed to do tool call, trying to parse raw response: {raw}')- return response, parsed-- # If it's not a recognized error type, log and raise- logger.error(f'Failed to invoke model: {str(e)}')- raise LLMException(401, 'LLM API call failed' + str(e)) from e--@cachedef get_browser_use_version() -> str:"""Get the browser-use package version using the same logic as Agent._set_browser_use_version_and_source"""diff --git a/docs/customize/agent-settings.mdx b/docs/customize/agent-settings.mdxindex 107d4e5f6..008c5e856 100644--- a/docs/customize/agent-settings.mdx+++ b/docs/customize/agent-settings.mdx@@ -12,7 +12,7 @@ The `Agent` class is the core component of Browser Use that handles browser auto```pythonfrom browser_use import Agent-from langchain_openai import ChatOpenAI+from browser_use.llm import ChatOpenAIagent = Agent(task="Search for latest news about AI",@@ -23,7 +23,7 @@ agent = Agent(### Required Parameters- `task`: The instruction for the agent to execute-- `llm`: A LangChain chat model instance. See <a href="/customize/supported-models">LangChain Models</a> for supported models.+- `llm`: A chat model instance. See <a href="/customize/supported-models">Supported Models</a> for supported models.## Agent Behavior@@ -56,16 +56,14 @@ agent = Agent(support.</Note>-### Reuse Existing Browser ContextBy default browser-use launches its own builtin browser using playwright chromium.-You can also connect to a remote browser or pass any of the following+You can also connect to a remote browser or pass any of the followingexisting playwright objects to the Agent: `page`, `browser_context`, `browser`, `browser_session`, or `browser_profile`.These all get passed down to create a `BrowserSession` for the `Agent`:-```pythonagent = Agent(task='book a flight to fiji',@@ -92,6 +90,7 @@ agent = Agent(```For example, to connect to an existing browser over CDP you could do:+```pythonagent = Agent(...@@ -100,6 +99,7 @@ agent = Agent(```For example, to connect to a local running chrome instance you can do:+```pythonagent = Agent(...@@ -110,8 +110,9 @@ agent = Agent(See <a href="/customize/real-browser">Connect to your Browser</a> for more info.<Note>- You can reuse the same `BrowserSession` after an agent has completed running. If you do nothing, the- browser will be automatically closed on `run()` completion only if it was launched by us.+ You can reuse the same `BrowserSession` after an agent has completed running.+ If you do nothing, the browser will be automatically closed on `run()`+ completion only if it was launched by us.</Note>## Running the Agent@@ -153,8 +154,10 @@ The `AgentHistoryList` provides many helper methods to analyze the execution:</Note>## Run initial actions without LLM+With [this example](https://github.com/browser-use/browser-use/blob/main/examples/features/initial_actions.py) you can run initial actions without the LLM.Specify the action as a dictionary where the key is the action name and the value is the action parameters. You can find all our actions in the [Controller](https://github.com/browser-use/browser-use/blob/main/browser_use/controller/service.py) source code.+```pythoninitial_actions = [@@ -174,7 +177,7 @@ agent = Agent(You can configure the agent and provide a separate message to help the LLM understand the task better.```python-from langchain_openai import ChatOpenAI+from browser_use.llm import ChatOpenAIagent = Agent(task="your task",@@ -188,7 +191,7 @@ agent = Agent(You can configure the agent to use a separate planner model for high-level task planning:```python-from langchain_openai import ChatOpenAI+from browser_use.llm import ChatOpenAI# Initialize modelsllm = ChatOpenAI(model='gpt-4o')@@ -205,17 +208,19 @@ agent = Agent(### Planner Parameters-- `planner_llm`: A LangChain chat model instance used for high-level task planning. Can be a smaller/cheaper model than the main LLM.+- `planner_llm`: A chat model instance used for high-level task planning. Can be a smaller/cheaper model than the main LLM.- `use_vision_for_planner`: Enable/disable vision capabilities for the planner model. Defaults to `True`.- `planner_interval`: Number of steps between planning phases. Defaults to `1`.Using a separate planner model can help:+- Reduce costs by using a smaller model for high-level planning- Improve task decomposition and strategic thinking- Better handle complex, multi-step tasks<Note>- The planner model is optional. If not specified, the agent will not use the planner model.+ The planner model is optional. If not specified, the agent will not use the+ planner model.</Note>### Optional Parameters@@ -226,6 +231,7 @@ Using a separate planner model can help:- `max_failures`: Maximum number of failures before giving up. Defaults to `3`.- `retry_delay`: Time to wait between retries in seconds when rate limited. Defaults to `10`.- `generate_gif`: Enable/disable GIF generation. Defaults to `False`. Set to `True` or a string path to save the GIF.+## Memory ManagementBrowser Use includes a procedural memory system using [Mem0](https://mem0.ai) that automatically summarizes the agent's conversation history at regular intervals to optimize context window usage during long tasks.@@ -256,7 +262,7 @@ You must configure the memory system using the `MemoryConfig` Pydantic model for```pythonfrom browser_use.agent.memory import MemoryConfig-from langchain_openai import ChatOpenAI # Assuming llm is an instance of ChatOpenAI+from browser_use.llm import ChatOpenAI # Assuming llm is an instance of ChatOpenAIllm_for_agent = ChatOpenAI(model="gpt-4o")@@ -286,18 +292,22 @@ agent = Agent(The `MemoryConfig` model provides these configuration options:#### Memory Settings+- `agent_id`: Unique identifier for the agent (default: `"browser_use_agent"`). Essential for persistent memory sessions if using a persistent vector store.- `memory_interval`: Number of steps between memory summarization (default: `10`)#### LLM Settings (for Mem0's internal operations)-- `llm_instance`: The LangChain `BaseChatModel` instance that Mem0 will use for its internal summarization and processing. You must pass the same LLM instance used by the main agent, or another compatible one, here.++- `llm_instance`: The `BaseChatModel` instance that Mem0 will use for its internal summarization and processing. You must pass the same LLM instance used by the main agent, or another compatible one, here.#### Embedder Settings+- `embedder_provider`: Provider for embeddings (`'openai'`, `'gemini'`, `'ollama'`, or `'huggingface'`)- `embedder_model`: Model name for the embedder- `embedder_dims`: Dimensions for the embeddings#### Vector Store Settings+- `vector_store_provider`: Choose the vector store backend. Supported options include:`'faiss'` (default), `'qdrant'`, `'pinecone'`, `'supabase'`, `'elasticsearch'`, `'chroma'`, `'weaviate'`, `'milvus'`, `'pgvector'`, `'upstash_vector'`, `'vertex_ai_vector_search'`, `'azure_ai_search'`, `'lancedb'`, `'mongodb'`, `'redis'`, `'memory'` (in-memory, non-persistent).- `vector_store_collection_name`: (Optional) Specify a custom name for the collection or index in your vector store. If not provided, a default name is generated (especially for local stores like FAISS/Chroma) or used by Mem0.@@ -305,16 +315,20 @@ The `MemoryConfig` model provides these configuration options:- `vector_store_config_override`: (Optional) A dictionary to provide or override specific configuration parameters required by Mem0 for the chosen `vector_store_provider`. This is where you'd put connection details like `host`, `port`, `api_key`, `url`, `environment`, etc., for cloud-based or server-based vector stores.The model automatically sets appropriate defaults based on the LLM being used:+- For `ChatOpenAI`: Uses OpenAI's `text-embedding-3-small` embeddings- For `ChatGoogleGenerativeAI`: Uses Gemini's `models/text-embedding-004` embeddings- For `ChatOllama`: Uses Ollama's `nomic-embed-text` embeddings- Default: Uses Hugging Face's `all-MiniLM-L6-v2` embeddings<Note>- **Important:**- - Always pass a properly constructed `MemoryConfig` object to the `memory_config` parameter.- - Ensure the `llm_instance` is provided to `MemoryConfig` so Mem0 can perform its operations.- - For persistent memory across agent runs or for shared memory, choose a scalable vector store provider (like Qdrant, Pinecone, etc.) and configure it correctly using `vector_store_provider` and `vector_store_config_override`. The default 'faiss' provider stores data locally in `vector_store_base_path`.+ **Important:** - Always pass a properly constructed `MemoryConfig` object to+ the `memory_config` parameter. - Ensure the `llm_instance` is provided to+ `MemoryConfig` so Mem0 can perform its operations. - For persistent memory+ across agent runs or for shared memory, choose a scalable vector store+ provider (like Qdrant, Pinecone, etc.) and configure it correctly using+ `vector_store_provider` and `vector_store_config_override`. The default+ 'faiss' provider stores data locally in `vector_store_base_path`.</Note>### How Memory Works@@ -326,7 +340,6 @@ When enabled, the agent periodically compresses its conversation history into co3. The original messages in the agent's active context are replaced with this summary, reducing token usage.4. This process helps maintain important context while freeing up the context window for new information.-### Disabling MemoryIf you want to disable the memory system (for debugging or for shorter tasks), set `enable_memory` to `False`:diff --git a/docs/customize/hooks.mdx b/docs/customize/hooks.mdxindex c95b913f8..d27673a58 100644--- a/docs/customize/hooks.mdx+++ b/docs/customize/hooks.mdx@@ -8,15 +8,14 @@ author: "Carlos A. Planchón"Browser-Use provides lifecycle hooks that allow you to execute custom code at specific points during the agent's execution.Hook functions can be used to read and modify agent state while running, implement custom logic, change configuration, integrate the Agent with external applications.-## Available HooksCurrently, Browser-Use provides the following hooks:-| Hook | Description | When it's called |-| ---- | ----------- | ---------------- |-| `on_step_start` | Executed at the beginning of each agent step | Before the agent processes the current state and decides on the next action |-| `on_step_end` | Executed at the end of each agent step | After the agent has executed all the actions for the current step, before it starts the next step |+| Hook | Description | When it's called |+| --------------- | -------------------------------------------- | ------------------------------------------------------------------------------------------------- |+| `on_step_start` | Executed at the beginning of each agent step | Before the agent processes the current state and decides on the next action |+| `on_step_end` | Executed at the end of each agent step | After the agent has executed all the actions for the current step, before it starts the next step |```pythonawait agent.run(on_step_start=..., on_step_end=...)@@ -24,12 +23,11 @@ await agent.run(on_step_start=..., on_step_end=...)Each hook should be an `async` callable function that accepts the `agent` instance as its only parameter.-### Basic Example```pythonfrom browser_use import Agent-from langchain_openai import ChatOpenAI+from browser_use.llm import ChatOpenAIasync def my_step_hook(agent: Agent):@@ -37,23 +35,23 @@ async def my_step_hook(agent: Agent):# agent.settings, agent.state, agent.task# agent.controller, agent.llm, agent.browser_session# agent.pause(), agent.resume(), agent.add_new_task(...), etc.-+# You also have direct access to the playwright Page and Browser Contextpage = await agent.browser_session.get_current_page()# https://playwright.dev/python/docs/api/class-page-+current_url = page.urlvisit_log = agent.state.history.urls()previous_url = visit_log[-2] if len(visit_log) >= 2 else Noneprint(f"Agent was last on URL: {previous_url} and is now on {current_url}")-+# Example: listen for events on the page, interact with the DOM, run JS directly, etc.await page.on('domcontentloaded', lambda: print('page navigated to a new url...'))await page.locator("css=form > input[type=submit]").click()await page.evaluate('() => alert(1)')await page.browser.new_tabawait agent.browser_session.session.context.add_init_script('/* some JS to run on every page */')-+# Example: monitor or intercept all network requestsasync def handle_request(route):# Print, modify, block, etc. do anything to the requests here@@ -65,10 +63,10 @@ async def my_step_hook(agent: Agent):# Example: pause agent execution and resume it based on some custom codeif '/completed' in current_url:agent.pause()- Path('result.txt').write_text(await page.content())+ Path('result.txt').write_text(await page.content())input('Saved "completed" page content to result.txt, press [Enter] to resume...')agent.resume()-+agent = Agent(task="Search for the latest news about AI",llm=ChatOpenAI(model="gpt-4o"),@@ -87,24 +85,23 @@ When working with agent hooks, you have access to the entire `Agent` instance. H- `agent.task` lets you see what the main task is, `agent.add_new_task(...)` lets you queue up a new one- `agent.controller` give access to the `Controller()` object and `Registry()` containing the available actions- - `agent.controller.registry.execute_action('click_element_by_index', {'index': 123}, browser_session=agent.browser_session)`+ - `agent.controller.registry.execute_action('click_element_by_index', {'index': 123}, browser_session=agent.browser_session)`- `agent.context` lets you access any user-provided context object passed in to `Agent(context=...)`- `agent.sensitive_data` contains the sensitive data dict, which can be updated in-place to add/remove/modify items- `agent.settings` contains all the configuration options passed to the `Agent(...)` at init time- `agent.llm` gives direct access to the main LLM object (e.g. `ChatOpenAI`)- `agent.state` gives access to lots of internal state, including agent thoughts, outputs, actions, etc.- - `agent.state.history.model_thoughts()`: Reasoning from Browser Use's model.- - `agent.state.history.model_outputs()`: Raw outputs from the Browsre Use's model.- - `agent.state.history.model_actions()`: Actions taken by the agent- - `agent.state.history.extracted_content()`: Content extracted from web pages- - `agent.state.history.urls()`: URLs visited by the agent+ - `agent.state.history.model_thoughts()`: Reasoning from Browser Use's model.+ - `agent.state.history.model_outputs()`: Raw outputs from the Browsre Use's model.+ - `agent.state.history.model_actions()`: Actions taken by the agent+ - `agent.state.history.extracted_content()`: Content extracted from web pages+ - `agent.state.history.urls()`: URLs visited by the agent- `agent.browser_session` gives direct access to the `BrowserSession()` and playwright objects- - `agent.browser_session.get_current_page()`: Get the current playwright `Page` object the agent is focused on- - `agent.browser_session.browser_context`: Get the current playwright `BrowserContext` object- - `agent.browser_session.browser_context.pages`: Get all the tabs currently open in the context- - `agent.browser_session.get_page_html()`: Current page HTML- - `agent.browser_session.take_screenshot()`: Screenshot of the current page-+ - `agent.browser_session.get_current_page()`: Get the current playwright `Page` object the agent is focused on+ - `agent.browser_session.browser_context`: Get the current playwright `BrowserContext` object+ - `agent.browser_session.browser_context.pages`: Get all the tabs currently open in the context+ - `agent.browser_session.get_page_html()`: Current page HTML+ - `agent.browser_session.take_screenshot()`: Screenshot of the current page## Tips for Using Hooks@@ -123,11 +120,13 @@ This comprehensive example demonstrates a complete implementation for recordingTo use this example, you'll need to:1. Set up the required dependencies:+```bash- pip install fastapi uvicorn prettyprinter pyobjtojson dotenv browser-use langchain-openai+ pip install fastapi uvicorn prettyprinter pyobjtojson dotenv browser-use```2. Create two separate Python files:+- `api.py` - The FastAPI server component- `client.py` - The Browser-Use agent with recording hook@@ -145,7 +144,7 @@ The server component handles receiving and storing the agent's activity data:## FastAPI API to record and save Browser-Use activity data.# Save this code to api.py and run with `python api.py`-#+#import jsonimport base64@@ -161,7 +160,7 @@ prettyprinter.install_extras()def b64_to_png(b64_string: str, output_file):"""Convert a Base64-encoded string to a PNG file.-+:param b64_string: A string containing Base64-encoded data:param output_file: The path to the output PNG file"""@@ -233,7 +232,7 @@ import asyncioimport requestsfrom dotenv import load_dotenvfrom pyobjtojson import obj_to_json-from langchain_openai import ChatOpenAI+from browser_use.llm import ChatOpenAIfrom browser_use import Agent# Load environment variables (for API keys)@@ -258,7 +257,7 @@ async def record_activity(agent_obj):extracted_content_json_last_elem = Noneprint('--- ON_STEP_START HOOK ---')-+# Capture current page statewebsite_html = await agent_obj.browser_session.get_page_html()website_screenshot = await agent_obj.browser_session.take_screenshot()@@ -328,7 +327,7 @@ async def record_activity(agent_obj):print("--- MODEL STEP SUMMARY ---")print(f"URL: {urls_json_last_elem}")-+# Send data to the APIresult = send_agent_history_step(data=model_step_summary)print(f"Recording API response: {result}")@@ -340,7 +339,7 @@ async def run_agent():task="Compare the price of gpt-4o and DeepSeek-V3",llm=ChatOpenAI(model="gpt-4o"),)-+try:print("Starting Browser-Use agent with recording hook")await agent.run(@@ -358,7 +357,7 @@ if __name__ == "__main__":print("Recording API is available")except:print("Warning: Recording API may not be running. Start api.py first.")-+# Run the agentasyncio.run(run_agent())```diff --git a/docs/customize/real-browser.mdx b/docs/customize/real-browser.mdxindex 0c6470f4c..5e7deaa80 100644--- a/docs/customize/real-browser.mdx+++ b/docs/customize/real-browser.mdx@@ -14,9 +14,10 @@ Browser Use supports a wide variety of ways to launch or connect to a browser:- Connect to a local browser already running using `browser_pid`<Tip>-Don't want to manage your own browser infrastructure? Try [☁️ Browser Use Cloud](https://browser-use.com) ➡️+Don't want to manage your own browser infrastructure? Try [☁️ Browser Use Cloud](https://browser-use.com) ➡️We provide automatic CAPTCHA solving, proxies, human-in-the-loop automation, and more!+</Tip>## Connection Methods@@ -34,7 +35,7 @@ browser_session = BrowserSession(executable_path='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', # macOS# For Windows: 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe'# For Linux: '/usr/bin/google-chrome'-+# Use a specific data directory on disk (optional, set to None for incognito)user_data_dir='~/.config/browseruse/profiles/default', # this is the default# ... any other BrowserProfile or playwright launch_persistnet_context config...@@ -51,7 +52,15 @@ agent = Agent(We support most `chromium`-based browsers in `executable_path`, including [Brave](https://github.com/browser-use/browser-use/tree/main/examples/browser/stealth.py), [patchright chromium](https://github.com/Kaliiiiiiiiii-Vinyzu/patchright), [rebrowser](https://rebrowser.net/), Edge, and more. See [`examples/browser/stealth.py`](https://github.com/browser-use/browser-use/tree/main/examples/browser) for more. We do not support Firefox or Safari at the moment.<Warning>- [As of Chrome v136](https://github.com/browser-use/browser-use/issues/1520), driving browsers with the default profile is [no longer supported](https://developer.chrome.com/blog/remote-debugging-port) for security reasons. Browser-Use has transitioned to creating a new dedicated profile for agents in: `~/.config/browseruse/profiles/default`. You can [open this profile](https://superuser.com/questions/377186/how-do-i-start-chrome-using-a-specified-user-profile) and log into everything you need your agent to have access to, and it will persist over time.+ [As of Chrome v136](https://github.com/browser-use/browser-use/issues/1520),+ driving browsers with the default profile is [no longer+ supported](https://developer.chrome.com/blog/remote-debugging-port) for+ security reasons. Browser-Use has transitioned to creating a new dedicated+ profile for agents in: `~/.config/browseruse/profiles/default`. You can [open+ this+ profile](https://superuser.com/questions/377186/how-do-i-start-chrome-using-a-specified-user-profile)+ and log into everything you need your agent to have access to, and it will+ persist over time.</Warning>### Method B: Connect Using Existing Playwright Objects@@ -67,7 +76,7 @@ async with async_playwright() as playwright:browser = await playwright.chromium.launch()context = await browser.new_context()page = await context.new_page()-+browser_session = BrowserSession(page=page,# browser_context=context, # all these are supported@@ -146,8 +155,6 @@ agent = Agent()```--## Security Considerations<Warning>@@ -164,6 +171,7 @@ agent = Agent(## Best Practices1. **Use isolated profiles**: Create separate Chrome profiles for different agents to limit scope of risk:+```pythonbrowser_session = BrowserSession(user_data_dir='~/.config/browseruse/profiles/banking',@@ -172,6 +180,7 @@ agent = Agent(```2. **Limit domain access**: Restrict which sites the agent can visit:+```pythonbrowser_session = BrowserSession(allowed_domains=['example.com', 'http*://*.github.com'],@@ -194,7 +203,7 @@ agent = Agent(## Re-Using a Browser-A `BrowserSession` starts when the browser is launched/connected, and ends when the browser process exits/disconnects. A session internally manages a single live playwright browser context, and is normally auto-closed by the agent when its task is complete (*if* the agent started the session itself). If you pass an existing `BrowserSession` into an Agent, or if you set `BrowserSession(keep_alive=True)`, the session will not be closed and can be re-used between agents.+A `BrowserSession` starts when the browser is launched/connected, and ends when the browser process exits/disconnects. A session internally manages a single live playwright browser context, and is normally auto-closed by the agent when its task is complete (_if_ the agent started the session itself). If you pass an existing `BrowserSession` into an Agent, or if you set `BrowserSession(keep_alive=True)`, the session will not be closed and can be re-used between agents.Browser Use provides a number of ways to re-use profiles, sessions, and other configuration across multiple agents.@@ -206,7 +215,9 @@ Browser Use provides a number of ways to re-use profiles, sessions, and other co- ⚠️ parallel agents can share a single `BrowserSession`, working in the same tab<Important>-Multiple `BrowserSession`s (aka chrome processes) cannot share the same `user_data_dir` at the same time, but they can share a `storage_state` file or `BrowserProfile` config.+ Multiple `BrowserSession`s (aka chrome processes) cannot share the same+ `user_data_dir` at the same time, but they can share a `storage_state` file or+ `BrowserProfile` config.</Important>### Sequential Agents, Same Profile, Different Browser@@ -215,7 +226,7 @@ If you are only running one agent & browser at a time, they can re-use the same```pythonfrom browser_use import Agent, BrowserSession-from langchain_openai import ChatOpenAI+from browser_use.llm import ChatOpenAIreused_profile = BrowserProfile(user_data_dir='~/.config/browseruse/profiles/default')@@ -243,7 +254,7 @@ Each agent will start off looking at the same tab the last agent ended off on.```pythonfrom browser_use import Agent, BrowserSession-from langchain_openai import ChatOpenAI+from browser_use.llm import ChatOpenAIreused_session = BrowserSession(user_data_dir='~/.config/browseruse/profiles/default',@@ -272,7 +283,7 @@ await reused_session.close()```pythonfrom browser_use import Agent, BrowserSession-from langchain_openai import ChatOpenAI+from browser_use.llm import ChatOpenAIshared_browser = BrowserSession(storage_state='/tmp/cookies.json',@@ -300,13 +311,14 @@ await shared_browser.close()### Parallel Agents, Same Browser, Same Tab<Warning>-⚠️ This mode is not recommended. Agents are not yet optimized to share the same tab in the same browser, they may interfere with each other or cause errors.+ ⚠️ This mode is not recommended. Agents are not yet optimized to share the+ same tab in the same browser, they may interfere with each other or cause+ errors.</Warning>-```pythonfrom browser_use import Agent, BrowserSession-from langchain_openai import ChatOpenAI+from browser_use.llm import ChatOpenAIfrom playwright.async_api import async_playwrightplaywright = await async_playwright().start()@@ -335,9 +347,7 @@ await shared_session.kill()### Parallel Agents, Same Profile, Different Browsers-<Tip>-This mode is the recommended default.-</Tip>+<Tip>This mode is the recommended default.</Tip>To share a single set of configuration or cookies, but still have agents working in their own browser sessions (potentially in parallel), use our provided `BrowserProfile` object.@@ -402,7 +412,8 @@ If you get a "profile is already in use" error:3. Alternatively, manually delete the `SingletonLock` file in the profile directory<Note>- For more configuration options, see the [Browser Settings](/customize/browser-settings) documentation.+ For more configuration options, see the [Browser+ Settings](/customize/browser-settings) documentation.</Note>### Profile Version Issuesdiff --git a/docs/customize/sensitive-data.mdx b/docs/customize/sensitive-data.mdxindex 5c88782aa..c536f8bd6 100644--- a/docs/customize/sensitive-data.mdx+++ b/docs/customize/sensitive-data.mdx@@ -34,10 +34,10 @@ Here's a basic example of how to use sensitive data:from dotenv import load_dotenvload_dotenv()-from langchain_openai import ChatOpenAI+from browser_use.llm import ChatOpenAIfrom browser_use import Agent, BrowserSession-llm = ChatOpenAI(model='gpt-4o', temperature=0.0)+llm = ChatOpenAI(model='gpt-4.1')# Define sensitive data# The LLM will only see placeholder names (x_member_number, x_passphrase), never the actual values@@ -89,7 +89,7 @@ This approach ensures that sensitive information remains secure while still allo- Always restrict your sensitive data to only the exact domains that need it, `https://travel.example.com` is better than `*.example.com`- Always restrict [`BrowserSession(allowed_domains=[...])`](https://docs.browser-use.com/customize/browser-settings#allowed-domains) to only the domains the agent needs to visit to accomplish its task. This helps guard against prompt injection attacks, jailbreaks, and LLM mistakes.- Only use `sensitive_data` for strings that can be inputted verbatim as text. The LLM never sees the actual values, so it can't "understand" them, adapt them, or split them up for multiple input fields. For example, you can't ask the Agent to click through a datepicker UI to input the sensitive value `1990-12-31`. For these situations you can implement a [custom function](/customize/custom-functions) the LLM can call that updates the DOM using Python / JS.-- Don't use `sensitive_data` for login credentials, it's better to use [`storage_state`](docs.browser-use.com/customize/browser-settings#storage-state) or a [`user_data_dir`](/customize/browser-settings#user-data-dir) to log into the sites the agent needs in advance & reuse the cookies:+- Don't use `sensitive_data` for login credentials, it's better to use [`storage_state`](docs.browser-use.com/customize/browser-settings#storage-state) or a [`user_data_dir`](/customize/browser-settings#user-data-dir) to log into the sites the agent needs in advance & reuse the cookies:```bash# open a browser to log into the sites you need & save the cookies@@ -110,11 +110,9 @@ It's recommended to set `Agent(use_vision=False)` when working with `sensitive_d</Warning>-<a name="allowed_domains"></a><a name="domain-pattern-format"></a>-### Allowed DomainsDomain patterns in `sensitive_data` follow the same format as [`allowed_domains`](https://docs.browser-use.com/customize/browser-settings#allowed-domains):@@ -125,7 +123,7 @@ Domain patterns in `sensitive_data` follow the same format as [`allowed_domains`- `chrome-extension://*` - Matches any Chrome extension URL e.g. `chrome-extension://anyextensionid/options.html`> **Security Warning**: For security reasons, certain patterns are explicitly rejected:->+>> - Wildcards in TLD part (e.g., `example.*`) are **not allowed** (`google.*` would match `google.ninja`, `google.pizza`, etc. which is a bad idea)> - Embedded wildcards (e.g., `g*e.com`) are rejected to prevent overly broad matches> - Multiple wildcards like `*.*.domain` are not supported currently, open an issue if you need this feature@@ -142,7 +140,6 @@ When working with sensitive data, keep these details in mind:- If you provide an empty value for a key in the `sensitive_data` dictionary, it will be treated the same as a missing key.- The system will always attempt to process all valid substitutions, even if some keys are missing or empty.----### Full Example@@ -153,11 +150,11 @@ Here's a more complex example demonstrating multiple domains and sensitive datafrom dotenv import load_dotenvload_dotenv()-from langchain_openai import ChatOpenAI+from browser_use.llm import ChatOpenAIfrom browser_use import Agent, BrowserSession-llm = ChatOpenAI(model='gpt-4o', temperature=0.0)+llm = ChatOpenAI(model='gpt-4.1')# Domain-specific sensitive datasensitive_data = {diff --git a/docs/customize/supported-models.mdx b/docs/customize/supported-models.mdxindex 459e846dd..e437845bb 100644--- a/docs/customize/supported-models.mdx+++ b/docs/customize/supported-models.mdx@@ -1,40 +1,46 @@---title: "Supported Models"-description: "Guide to using different LangChain chat models with Browser Use"+description: "Guide to using different chat models with Browser Use"icon: "robot"---## Overview-Browser Use supports various LangChain chat models. Here's how to configure and use the most popular ones. The full list is available in the [LangChain documentation](https://python.langchain.com/docs/integrations/chat/).+Here's how to configure the models.-## Model Recommendations+### Migration from Langchain-We have yet to test performance across all models. Currently, we achieve the best results using GPT-4o with an 89% accuracy on the [WebVoyager Dataset](https://browser-use.com/posts/sota-technical-report). DeepSeek-V3 is 30 times cheaper than GPT-4o. Gemini-2.0-exp is also gaining popularity in the community because it is currently free.-We also support local models, like Qwen 2.5, but be aware that small models often return the wrong output structure-which lead to parsing errors. We believe that local models will improve significantly this year.+We have recently switched from Langchain to our own implementation of the models. To migrate the previous code, just replace `from langchain_openai import ChatOpenAI` with `from browser_use.llm import ChatOpenAI` etc. The methods should be compatible(ish).+## Model Recommendations-<Note>- All models require their respective API keys. Make sure to set them in your- environment variables before running the agent.-</Note>+We recommend using GPT-4.1 for the best performance (best accuracy ~$0.01 per step). The best price to performance can be achieved using `gemini-2.0-flash-exp` (currently also the most popular model, costs ~$0.001 per step).## Supported Models-All LangChain chat models, which support tool-calling are available. We will document the most popular ones here.+Our library natively supports the following models:++- OpenAI+- Anthropic+- Azure OpenAI+- Gemini+- Groq++We also support all other models that can be called via OpenAI compatible API (deepseek, novita, x, qwen). Please open a PR if you want to add a model.++We have natively switched to structured output when possible,### OpenAI-OpenAI's GPT-4o models are recommended for best performance.+OpenAI's GPT-4.1 models are recommended for best performance.```python-from langchain_openai import ChatOpenAI+from browser_use.llm import ChatOpenAIfrom browser_use import Agent# Initialize the modelllm = ChatOpenAI(- model="gpt-4o",- temperature=0.0,+ model="gpt-4.1",)# Create agent with the model@@ -52,16 +58,13 @@ OPENAI_API_KEY=### Anthropic-```python-from langchain_anthropic import ChatAnthropic+from browser_use.llm import ChatAnthropicfrom browser_use import Agent# Initialize the modelllm = ChatAnthropic(model_name="claude-3-5-sonnet-20240620",- temperature=0.0,- timeout=100, # Increase for complex tasks)# Create agent with the model@@ -80,17 +83,14 @@ ANTHROPIC_API_KEY=### Azure OpenAI```python-from langchain_openai import AzureChatOpenAI+from browser_use.llm import ChatAzureOpenAIfrom browser_use import Agentfrom pydantic import SecretStrimport os# Initialize the model-llm = AzureChatOpenAI(- model="gpt-4o",- api_version='2024-10-21',- azure_endpoint=os.getenv('AZURE_OPENAI_ENDPOINT', ''),- api_key=SecretStr(os.getenv('AZURE_OPENAI_KEY', '')),+llm = ChatAzureOpenAI(+ model="gpt-4.1",)# Create agent with the model@@ -104,17 +104,15 @@ Required environment variables:```bash .envAZURE_OPENAI_ENDPOINT=https://your-endpoint.openai.azure.com/-AZURE_OPENAI_KEY=+AZURE_OPENAI_API_KEY=```-### Gemini-> [!IMPORTANT]-> `GEMINI_API_KEY` was the old environment var name, it should be called `GOOGLE_API_KEY` as of 2025-05.+> [!IMPORTANT] > `GEMINI_API_KEY` was the old environment var name, it should be called `GOOGLE_API_KEY` as of 2025-05.```python-from langchain_google_genai import ChatGoogleGenerativeAI+from browser_use.llm import ChatGooglefrom browser_use import Agentfrom dotenv import load_dotenv@@ -122,7 +120,7 @@ from dotenv import load_dotenvload_dotenv()# Initialize the model-llm = ChatGoogleGenerativeAI(model='gemini-2.0-flash-exp')+llm = ChatGoogle(model='gemini-2.0-flash-exp')# Create agent with the modelagent = Agent(@@ -137,159 +135,22 @@ Required environment variables:GOOGLE_API_KEY=```--### DeepSeek-V3-The community likes DeepSeek-V3 for its low price, no rate limits, open-source nature, and good performance.-The example is available [here](https://github.com/browser-use/browser-use/blob/main/examples/models/deepseek.py).--```python-from langchain_deepseek import ChatDeepSeek-from browser_use import Agent-from pydantic import SecretStr-from dotenv import load_dotenv-import os--load_dotenv()-api_key = os.getenv("DEEPSEEK_API_KEY")--# Initialize the model-llm=ChatDeepSeek(base_url='https://api.deepseek.com/v1', model='deepseek-chat', api_key=SecretStr(api_key))--# Create agent with the model-agent = Agent(- task="Your task here",- llm=llm,- use_vision=False-)-```--Required environment variables:--```bash .env-DEEPSEEK_API_KEY=-```--### DeepSeek-R1-We support DeepSeek-R1. Its not fully tested yet, more and more functionality will be added, like e.g. the output of it'sreasoning content.-The example is available [here](https://github.com/browser-use/browser-use/blob/main/examples/models/deepseek-r1.py).-It does not support vision. The model is open-source so you could also use it with Ollama, but we have not tested it.-```python-from langchain_deepseek import ChatDeepSeek-from browser_use import Agent-from pydantic import SecretStr-from dotenv import load_dotenv-import os--load_dotenv()-api_key = os.getenv("DEEPSEEK_API_KEY")--# Initialize the model-llm=ChatDeepSeek(base_url='https://api.deepseek.com/v1', model='deepseek-reasoner', api_key=SecretStr(api_key))--# Create agent with the model-agent = Agent(- task="Your task here",- llm=llm,- use_vision=False-)-```--Required environment variables:--```bash .env-DEEPSEEK_API_KEY=-```--### Ollama-Many users asked for local models. Here they are.--1. Download Ollama from [here](https://ollama.ai/download)-2. Run `ollama pull model_name`. Pick a model which supports tool-calling from [here](https://ollama.com/search?c=tools)-3. Run `ollama start`+## Groq```python-from langchain_ollama import ChatOllama+from browser_use.llm import ChatGroqfrom browser_use import Agent-from pydantic import SecretStr+llm = ChatGroq(model="meta-llama/llama-4-maverick-17b-128e-instruct")-# Initialize the model-llm=ChatOllama(model="qwen2.5", num_ctx=32000)--# Create agent with the modelagent = Agent(task="Your task here",llm=llm)```-Required environment variables: None!--### Novita AI-[Novita AI](https://novita.ai) is an LLM API provider that offers a wide range of models. Note: choose a model that supports function calling.--```python-from langchain_openai import ChatOpenAI-from browser_use import Agent-from pydantic import SecretStr-from dotenv import load_dotenv-import os--load_dotenv()-api_key = os.getenv("NOVITA_API_KEY")--# Initialize the model-llm = ChatOpenAI(base_url='https://api.novita.ai/v3/openai', model='deepseek/deepseek-v3-0324', api_key=SecretStr(api_key))--# Create agent with the model-agent = Agent(- task="Your task here",- llm=llm,- use_vision=False-)-```-Required environment variables:```bash .env-NOVITA_API_KEY=+GROQ_API_KEY=```-### X AI-[X AI](https://x.ai) is an LLM API provider that offers a wide range of models. Note: choose a model that supports function calling.--```python-from langchain_openai import ChatOpenAI-from browser_use import Agent-from pydantic import SecretStr-from dotenv import load_dotenv-import os--load_dotenv()-api_key = os.getenv("GROK_API_KEY")--# Initialize the model-llm = ChatOpenAI(- base_url='https://api.x.ai/v1',- model='grok-3-beta',- api_key=SecretStr(api_key)-)--# Create agent with the model-agent = Agent(- task="Your task here",- llm=llm,- use_vision=False-)-```--Required environment variables:--```bash .env-GROK_API_KEY=-```--## Coming soon-(We are working on it)-- Groq-- Github-- Fine-tuned modelsdiff --git a/docs/development/local-setup.mdx b/docs/development/local-setup.mdxindex 559060ee7..d4442782a 100644--- a/docs/development/local-setup.mdx+++ b/docs/development/local-setup.mdx@@ -94,9 +94,8 @@ BROWSER_USE_LOGGING_LEVEL=debug # Helpful for development```<Note>- You can use any LLM model supported by LangChain. See- [LangChain Models](/customize/supported-models) for available options and their specific- API key requirements.+ See [Supported Models](/customize/supported-models) for available LLM options+ and their specific API key requirements.</Note>## Development@@ -154,6 +153,7 @@ If you run into any issues:2. Join our [Discord community](https://link.browser-use.com/discord) for support<Note>- We welcome contributions! See our [Contribution Guide](/development/contribution-guide) for guidelines on how to help improve+ We welcome contributions! See our [Contribution+ Guide](/development/contribution-guide) for guidelines on how to help improveBrowser Use.</Note>diff --git a/docs/development/observability.mdx b/docs/development/observability.mdxindex 874a80b65..68dd8ecd4 100644--- a/docs/development/observability.mdx+++ b/docs/development/observability.mdx@@ -10,7 +10,8 @@ Browser Use has a native integration with [Laminar](https://lmnr.ai) - open-sourRead more about Laminar in the [Laminar docs](https://docs.lmnr.ai).<Note>- Laminar excels at tracing browser agents by providing unified visibility into both browser session recordings and agent execution steps.+ Laminar excels at tracing browser agents by providing unified visibility into+ both browser session recordings and agent execution steps.</Note>## Setup@@ -18,6 +19,7 @@ Read more about Laminar in the [Laminar docs](https://docs.lmnr.ai).To setup Laminar, you need to install the `lmnr` package and set the `LMNR_PROJECT_API_KEY` environment variable.To get your project API key, you can either:+- Register on [Laminar Cloud](https://lmnr.ai) and get the key from your project settings- Or spin up a local Laminar instance and get the key from the settings page@@ -31,7 +33,7 @@ export LMNR_PROJECT_API_KEY=<your-project-api-key>Then, you simply initialize the Laminar at the top of your project and both Browser Use and session recordings will be automatically traced.```python {5-8}-from langchain_openai import ChatOpenAI+from browser_use.llm import ChatOpenAIfrom browser_use import Agentimport asyncio@@ -60,7 +62,6 @@ In the trace view, you can also see the agent's current step, the tool it's usin<img className="block" src="/images/laminar.png" alt="Laminar" />-## LaminarTo learn more about tracing and evaluating your browser agents, check out the [Laminar docs](https://docs.lmnr.ai).diff --git a/docs/quickstart.mdx b/docs/quickstart.mdxindex aea07056a..3682424af 100644--- a/docs/quickstart.mdx+++ b/docs/quickstart.mdx@@ -43,7 +43,7 @@ uv run playwright installThen you can use the agent as follows:```python agent.py-from langchain_openai import ChatOpenAI+from browser_use.llm import ChatOpenAIfrom browser_use import Agentfrom dotenv import load_dotenvload_dotenv()@@ -65,12 +65,11 @@ asyncio.run(main())## Set up your LLM API keys-`ChatOpenAI` and other Langchain chat models require API keys. You should store these in your `.env` file. For example, for OpenAI and Anthropic, you can set the API keys in your `.env` file, such as:-+`ChatOpenAI` and other chat models require API keys. You should store these in your `.env` file. For example, for OpenAI and Anthropic, you can set the API keys in your `.env` file, such as:```bash .envOPENAI_API_KEY=ANTHROPIC_API_KEY=```-For other LLM models you can refer to the [Langchain documentation](https://python.langchain.com/docs/integrations/chat/) to find how to set them up with their specific API keys.+For other LLM models you can refer to the [Supported Models](/customize/supported-models) page to find how to set them up with their specific API keys.diff --git a/eval/judge_system.py b/eval/judge_system.pyindex 8a3157b5b..814eed9d4 100644--- a/eval/judge_system.py+++ b/eval/judge_system.py@@ -25,9 +25,18 @@ from enum import Enumfrom pathlib import Pathfrom typing import Any-from langchain_core.language_models.chat_models import BaseChatModelfrom PIL import Image+from browser_use.llm.base import BaseChatModel+from browser_use.llm.messages import (+ BaseMessage,+ ContentPartImageParam,+ ContentPartTextParam,+ ImageURL,+ SystemMessage,+ UserMessage,+)+logger = logging.getLogger(__name__)@@ -136,16 +145,31 @@ def encode_image(image_path: str) -> str:def truncate_text(text: str, max_length: int) -> str:- """Truncate text to maximum length with ellipsis."""+ """Truncate text to maximum length with eval system indicator."""if len(text) <= max_length:return text- return text[: max_length - 3] + '...'+ return text[: max_length - 23] + '...[cut for eval]...'def prepare_agent_steps(complete_history: list[dict]) -> list[str]:- """Extract and format agent steps, limiting each to 2000 characters."""+ """Extract and format agent steps, limiting each to 2000 characters.++ Excludes the last step if it contains a 'done' action, since that content+ is already included in the final_result.+ """+ # Check if last step contains a 'done' action+ history_to_process = complete_history.copy()+ if complete_history:+ last_step = complete_history[-1]+ if last_step.get('result'):+ for result in last_step['result']:+ if isinstance(result, dict) and result.get('is_done'):+ # Exclude the last step since it's a 'done' action+ history_to_process = complete_history[:-1]+ break+steps = []- for i, step in enumerate(complete_history):+ for i, step in enumerate(history_to_process):step_text = f'Step {i + 1}:\n'# Add model output if available@@ -171,12 +195,66 @@ def prepare_agent_steps(complete_history: list[dict]) -> list[str]:if step.get('state', {}).get('url'):step_text += f'URL: {step["state"]["url"]}\n'- # Truncate to 2000 characters- steps.append(truncate_text(step_text, 2000))+ # Truncate to 2000 characters, with eval system indicator if truncated+ if len(step_text) > 2000:+ step_text = step_text[:1997] + '...[cut for eval]...'++ steps.append(step_text)return steps+def are_images_identical(img_path1: str, img_path2: str) -> bool:+ """Check if two images are identical by comparing their content."""+ try:+ with Image.open(img_path1) as img1, Image.open(img_path2) as img2:+ # Convert to same format for comparison+ if img1.mode != img2.mode:+ img1 = img1.convert('RGB')+ img2 = img2.convert('RGB')++ # Compare sizes first (quick check)+ if img1.size != img2.size:+ return False++ # Compare pixel data+ return list(img1.getdata()) == list(img2.getdata())+ except Exception as e:+ logger.warning(f'Failed to compare images {img_path1} and {img_path2}: {e}')+ return False+++def filter_images(screenshot_paths: list[str], max_images: int) -> list[str]:+ """+ Filter screenshot paths to:+ 1. Never include the first image (always white)+ 2. Remove consecutive duplicate images+ 3. Return up to max_images from the end+ """+ if not screenshot_paths:+ return []++ # Skip the first image (always white)+ filtered_paths = screenshot_paths[1:] if len(screenshot_paths) > 1 else []++ if not filtered_paths:+ return []++ # Remove consecutive duplicates+ deduplicated_paths = [filtered_paths[0]] # Always include the first non-skipped image++ for i in range(1, len(filtered_paths)):+ current_path = filtered_paths[i]+ previous_path = filtered_paths[i - 1]++ # Only add if not identical to previous image+ if not are_images_identical(current_path, previous_path):+ deduplicated_paths.append(current_path)++ # Return last max_images images+ return deduplicated_paths[-max_images:] if len(deduplicated_paths) > max_images else deduplicated_paths++async def comprehensive_judge(task: str,complete_history: list[dict],@@ -194,24 +272,16 @@ async def comprehensive_judge(final_result_truncated = truncate_text(final_result or 'No final result', 40000)agent_steps = prepare_agent_steps(complete_history)- # Select last N images- selected_images = screenshot_paths[-max_images:] if screenshot_paths else []+ # Select and filter images+ selected_images = filter_images(screenshot_paths, max_images)# Encode images- encoded_images = []+ encoded_images: list[ContentPartImageParam] = []for img_path in selected_images:if Path(img_path).exists():encoded_img = encode_image(img_path)if encoded_img:- encoded_images.append(- {- 'type': 'image_url',- 'image_url': {- 'url': f'data:image/jpeg;base64,{encoded_img}',- 'detail': 'high',- },- }- )+ encoded_images.append(ContentPartImageParam(image_url=ImageURL(url=f'data:image/jpeg;base64,{encoded_img}')))# Construct the evaluation promptsystem_prompt = """You are an expert judge evaluating browser automation agent performance.@@ -301,24 +371,21 @@ Respond with EXACTLY this JSON structure (no additional text):Analyze this execution and respond with the exact JSON structure requested."""# Build messages- content_parts = [{'type': 'text', 'text': user_prompt}]+ content_parts: list[ContentPartTextParam | ContentPartImageParam] = [ContentPartTextParam(text=user_prompt)]content_parts.extend(encoded_images)- messages = [- {'role': 'system', 'content': system_prompt},- {'role': 'user', 'content': content_parts},+ messages: list[BaseMessage] = [+ SystemMessage(content=system_prompt),+ UserMessage(content=content_parts),]# Get structured responsetry:- response = await asyncio.to_thread(model.invoke, messages)+ response = await model.ainvoke(messages)# Parse the JSON response# Handle both string and list content types- if isinstance(response.content, list):- response_text = str(response.content[0]) if response.content else ''- else:- response_text = str(response.content)+ response_text = response.completionresponse_text = response_text.strip()# Try to extract JSON if wrapped in markdowndiff --git a/eval/service.py b/eval/service.pyindex 05f155ddd..e70d01dd4 100644--- a/eval/service.py+++ b/eval/service.py@@ -12,7 +12,7 @@# This is the LLM as a judge evaluation system from the OSU-NLP Group paper# Any adaptiations made should be explicitly stated here:# Adaptations:-# We are using our langchain wrapper for the OpenAI API+# We are using our own wrapper for the OpenAI API# This means we changed model.generate to model.invoke. The behavior of the model should be identical.# Added a Online_Mind2Web_eval_with_retry wrapper with retry logic in case of API rate limiting or other issues.@@ -56,6 +56,11 @@ import psutilfrom lmnr import AsyncLaminarClient, Laminar, observefrom PIL import Image+from browser_use.llm.anthropic.chat import ChatAnthropic+from browser_use.llm.base import BaseChatModel+from browser_use.llm.google.chat import ChatGoogle+from browser_use.llm.openai.chat import ChatOpenAI+MAX_IMAGE = 5@@ -651,12 +656,6 @@ class TaskResult:}-from langchain_anthropic import ChatAnthropic-from langchain_core.language_models.chat_models import BaseChatModel-from langchain_google_genai import ChatGoogleGenerativeAI-from langchain_openai import ChatOpenAI-from pydantic.types import SecretStr-from browser_use import ActionResult, Agent, BrowserProfile, BrowserSession, Controllerfrom browser_use.agent.memory import MemoryConfigfrom browser_use.agent.views import AgentHistoryList@@ -851,7 +850,7 @@ def create_controller(use_serp: bool = False):def get_llm(model_name: str):- """Instantiates the correct LangChain ChatModel based on the model name."""+ """Instantiates the correct ChatModel based on the model name."""if model_name not in SUPPORTED_MODELS:raise ValueError(f'Unsupported model: {model_name}. Supported models are: {list(SUPPORTED_MODELS.keys())}')@@ -866,30 +865,29 @@ def get_llm(model_name: str):)api_key = None- api_key_secret = SecretStr(api_key) if api_key else Nonematch provider:case 'openai':kwargs = {'model': config['model_name'], 'temperature': 0.0}# Must set temperatue=1 if model is gpt-o4-miniif model_name == 'gpt-o4-mini':kwargs['temperature'] = 1- if api_key_secret:- kwargs['api_key'] = api_key_secret+ if api_key:+ kwargs['api_key'] = api_keyreturn ChatOpenAI(**kwargs)case 'anthropic':kwargs = {'model_name': config['model_name'], 'temperature': 0.0, 'timeout': 100, 'stop': None}- if api_key_secret:- kwargs['api_key'] = api_key_secret+ if api_key:+ kwargs['api_key'] = api_keyreturn ChatAnthropic(**kwargs)case 'google':kwargs = {'model': config['model_name'], 'temperature': 0.0}- if api_key_secret:- kwargs['api_key'] = api_key_secret- return ChatGoogleGenerativeAI(**kwargs)+ if api_key:+ kwargs['api_key'] = api_key+ return ChatGoogle(**kwargs)case 'openai_compatible':kwargs = {'model': config['model_name'], 'base_url': config['base_url'], 'temperature': 0.0}- if api_key_secret:- kwargs['api_key'] = api_key_secret+ if api_key:+ kwargs['api_key'] = api_keyelif config.get('base_url'):logger.warning(f'API key for {model_name} at {config["base_url"]} is missing, but base_url is specified. Authentication may fail.'diff --git a/examples/browser/multiple_agents_same_browser.py b/examples/browser/multiple_agents_same_browser.pyindex 9cea98329..1205fcfa5 100644--- a/examples/browser/multiple_agents_same_browser.py+++ b/examples/browser/multiple_agents_same_browser.py@@ -9,11 +9,10 @@ from dotenv import load_dotenvload_dotenv()-from langchain_openai import ChatOpenAI-from browser_use import Agentfrom browser_use.browser.profile import BrowserProfilefrom browser_use.browser.session import BrowserSession+from browser_use.llm import ChatOpenAIasync def main():diff --git a/examples/browser/real_browser.py b/examples/browser/real_browser.pyindex 276f9591f..d3ad39435 100644--- a/examples/browser/real_browser.py+++ b/examples/browser/real_browser.py@@ -8,10 +8,9 @@ from dotenv import load_dotenvload_dotenv()-from langchain_openai import ChatOpenAI-from browser_use import Agentfrom browser_use.browser import BrowserProfile, BrowserSession+from browser_use.llm import ChatOpenAIbrowser_profile = BrowserProfile(# NOTE: you need to close your chrome browser - so that this can open your browser in debug modediff --git a/examples/browser/stealth.py b/examples/browser/stealth.pyindex 7b57a5186..be2f0485c 100644--- a/examples/browser/stealth.py+++ b/examples/browser/stealth.py@@ -12,11 +12,11 @@ from dotenv import load_dotenvload_dotenv()from imgcat import imgcat-from langchain_openai import ChatOpenAIfrom browser_use.browser import BrowserSessionfrom browser_use.browser.profile import BrowserProfilefrom browser_use.browser.types import async_patchright+from browser_use.llm import ChatOpenAIllm = ChatOpenAI(model='gpt-4o')diff --git a/examples/browser/using_cdp.py b/examples/browser/using_cdp.pyindex 6168f4204..fe090bcef 100644--- a/examples/browser/using_cdp.py+++ b/examples/browser/using_cdp.py@@ -21,11 +21,10 @@ from dotenv import load_dotenvload_dotenv()-from langchain_google_genai import ChatGoogleGenerativeAI-from pydantic import SecretStrfrom browser_use import Agent, Controllerfrom browser_use.browser import BrowserProfile, BrowserSession+from browser_use.llm import ChatGoogleapi_key = os.getenv('GOOGLE_API_KEY')if not api_key:@@ -45,7 +44,7 @@ async def main():task += ' and save the document as pdf'# Assert api_key is not None to satisfy type checkerassert api_key is not None, 'GOOGLE_API_KEY must be set'- model = ChatGoogleGenerativeAI(model='gemini-2.0-flash-exp', api_key=SecretStr(api_key))+ model = ChatGoogle(model='gemini-2.0-flash-exp', api_key=api_key)agent = Agent(task=task,llm=model,diff --git a/examples/custom-functions/2fa.py b/examples/custom-functions/2fa.pyindex b5a31cd3c..f5d4e537d 100644--- a/examples/custom-functions/2fa.py+++ b/examples/custom-functions/2fa.py@@ -10,9 +10,9 @@ from dotenv import load_dotenvload_dotenv()import pyotp # type: ignore-from langchain_openai import ChatOpenAIfrom browser_use import ActionResult, Agent, Controller+from browser_use.llm import ChatOpenAI# Set up logginglogging.basicConfig(level=logging.INFO)diff --git a/examples/custom-functions/action_filters.py b/examples/custom-functions/action_filters.pyindex fe957d06b..619d6ed94 100644--- a/examples/custom-functions/action_filters.py+++ b/examples/custom-functions/action_filters.py@@ -27,11 +27,10 @@ from dotenv import load_dotenvload_dotenv()-from langchain_openai import ChatOpenAI-from browser_use.agent.service import Agent, Controllerfrom browser_use.browser import BrowserSessionfrom browser_use.browser.types import Page+from browser_use.llm import ChatOpenAI# Initialize controller and registrycontroller = Controller()diff --git a/examples/custom-functions/advanced_search.py b/examples/custom-functions/advanced_search.pyindex cf13cdbfa..491c368de 100644--- a/examples/custom-functions/advanced_search.py+++ b/examples/custom-functions/advanced_search.py@@ -12,11 +12,11 @@ load_dotenv()import logging-from langchain_openai import ChatOpenAIfrom pydantic import BaseModelfrom browser_use import ActionResult, Agent, Controllerfrom browser_use.browser.profile import BrowserProfile+from browser_use.llm import ChatOpenAIlogger = logging.getLogger(__name__)diff --git a/examples/custom-functions/clipboard.py b/examples/custom-functions/clipboard.pyindex 6b7cba2d5..5f5d82cc1 100644--- a/examples/custom-functions/clipboard.py+++ b/examples/custom-functions/clipboard.py@@ -9,12 +9,12 @@ from dotenv import load_dotenvload_dotenv()import pyperclip-from langchain_openai import ChatOpenAIfrom browser_use import Agent, Controllerfrom browser_use.agent.views import ActionResultfrom browser_use.browser import BrowserProfile, BrowserSessionfrom browser_use.browser.types import Page+from browser_use.llm import ChatOpenAIbrowser_profile = BrowserProfile(headless=False,diff --git a/examples/custom-functions/custom_hooks_before_after_step.py b/examples/custom-functions/custom_hooks_before_after_step.pyindex 98bacc80f..8d4c7b873 100644--- a/examples/custom-functions/custom_hooks_before_after_step.py+++ b/examples/custom-functions/custom_hooks_before_after_step.py@@ -123,10 +123,10 @@ from dotenv import load_dotenvload_dotenv()import requests-from langchain_openai import ChatOpenAIfrom pyobjtojson import obj_to_json # type: ignorefrom browser_use import Agent+from browser_use.llm import ChatOpenAI# import prettyprinter# prettyprinter.install_extras()diff --git a/examples/custom-functions/extract_pdf_content.py b/examples/custom-functions/extract_pdf_content.pyindex 20ab2de47..87048b707 100755--- a/examples/custom-functions/extract_pdf_content.py+++ b/examples/custom-functions/extract_pdf_content.py@@ -16,13 +16,13 @@ load_dotenv()import asyncioimport logging-from langchain_openai import ChatOpenAIfrom mistralai import Mistral # type: ignorefrom pydantic import BaseModel, Fieldfrom browser_use import Agent, Controllerfrom browser_use.agent.views import ActionResultfrom browser_use.browser.context import BrowserContext+from browser_use.llm import ChatOpenAIif not os.getenv('OPENAI_API_KEY'):raise ValueError('OPENAI_API_KEY is not set. Please add it to your environment variables.')diff --git a/examples/custom-functions/file_upload.py b/examples/custom-functions/file_upload.pyindex aee4b6b60..624e926a2 100644--- a/examples/custom-functions/file_upload.py+++ b/examples/custom-functions/file_upload.py@@ -17,11 +17,10 @@ try:except Exception:pass-from langchain_openai import ChatOpenAI-from browser_use import Agent, Controllerfrom browser_use.agent.views import ActionResultfrom browser_use.browser import BrowserSession+from browser_use.llm import ChatOpenAIlogger = logging.getLogger(__name__)diff --git a/examples/custom-functions/hover_element.py b/examples/custom-functions/hover_element.pyindex d1ddcfcb9..4ff3826fb 100644--- a/examples/custom-functions/hover_element.py+++ b/examples/custom-functions/hover_element.py@@ -8,12 +8,12 @@ from dotenv import load_dotenvload_dotenv()-from langchain_openai import ChatOpenAIfrom pydantic import BaseModelfrom browser_use import Agent, Controllerfrom browser_use.agent.views import ActionResultfrom browser_use.browser import BrowserProfile, BrowserSession+from browser_use.llm import ChatOpenAIclass HoverAction(BaseModel):diff --git a/examples/custom-functions/notification.py b/examples/custom-functions/notification.pyindex 31dde9266..0d9f780a4 100644--- a/examples/custom-functions/notification.py+++ b/examples/custom-functions/notification.py@@ -8,9 +8,8 @@ from dotenv import load_dotenvload_dotenv()-from langchain_openai import ChatOpenAI-from browser_use import ActionResult, Agent, Controller+from browser_use.llm import ChatOpenAIcontroller = Controller()diff --git a/examples/custom-functions/onepassword_2fa.py b/examples/custom-functions/onepassword_2fa.pyindex f98f3767a..c34fd19b0 100644--- a/examples/custom-functions/onepassword_2fa.py+++ b/examples/custom-functions/onepassword_2fa.py@@ -9,10 +9,10 @@ from dotenv import load_dotenvload_dotenv()-from langchain_openai import ChatOpenAIfrom onepassword.client import Client # type: ignore # pip install onepassword-sdkfrom browser_use import ActionResult, Agent, Controller+from browser_use.llm import ChatOpenAI# Set up logginglogging.basicConfig(level=logging.INFO)diff --git a/examples/custom-functions/perplexity_search.py b/examples/custom-functions/perplexity_search.pyindex b87f71ce9..b306d5d2a 100644--- a/examples/custom-functions/perplexity_search.py+++ b/examples/custom-functions/perplexity_search.py@@ -10,11 +10,11 @@ load_dotenv()import logging-from langchain_openai import ChatOpenAIfrom pydantic import BaseModelfrom browser_use import ActionResult, Agent, Controllerfrom browser_use.browser.profile import BrowserProfile+from browser_use.llm import ChatOpenAIlogger = logging.getLogger(__name__)diff --git a/examples/custom-functions/save_to_file_hugging_face.py b/examples/custom-functions/save_to_file_hugging_face.pyindex 7e63591d8..284018cc3 100644--- a/examples/custom-functions/save_to_file_hugging_face.py+++ b/examples/custom-functions/save_to_file_hugging_face.py@@ -8,11 +8,11 @@ from dotenv import load_dotenvload_dotenv()-from langchain_openai import ChatOpenAIfrom pydantic import BaseModelfrom browser_use.agent.service import Agentfrom browser_use.controller.service import Controller+from browser_use.llm import ChatOpenAI# Initialize controller firstcontroller = Controller()diff --git a/examples/custom-functions/solve_amazon_captcha.py b/examples/custom-functions/solve_amazon_captcha.pyindex 7c8d3f756..f3edbf458 100644--- a/examples/custom-functions/solve_amazon_captcha.py+++ b/examples/custom-functions/solve_amazon_captcha.py@@ -9,12 +9,12 @@ from dotenv import load_dotenvload_dotenv()from amazoncaptcha import AmazonCaptcha # type: ignore-from langchain_openai import ChatOpenAIfrom browser_use import ActionResultfrom browser_use.agent.service import Agentfrom browser_use.browser import BrowserConfig, BrowserSessionfrom browser_use.controller.service import Controller+from browser_use.llm import ChatOpenAIbrowser_profile = BrowserConfig(headless=False)diff --git a/examples/features/click_fallback_options.py b/examples/features/click_fallback_options.pyindex 15603038b..e5306185a 100644--- a/examples/features/click_fallback_options.py+++ b/examples/features/click_fallback_options.py@@ -9,10 +9,9 @@ from dotenv import load_dotenvload_dotenv()from aiohttp import web # make sure to install aiohttp: pip install aiohttp-from langchain_openai import ChatOpenAI-# from langchain_google_genai import ChatGoogleGenerativeAIfrom browser_use import Agent, Controller+from browser_use.llm import ChatOpenAI# Define a simple HTML pageHTML_CONTENT = """diff --git a/examples/features/cross_origin_iframes.py b/examples/features/cross_origin_iframes.pyindex 0d59ec418..5a186e253 100644--- a/examples/features/cross_origin_iframes.py+++ b/examples/features/cross_origin_iframes.py@@ -14,10 +14,9 @@ from dotenv import load_dotenvload_dotenv()-from langchain_openai import ChatOpenAI-from browser_use import Agent, Controllerfrom browser_use.browser import BrowserProfile, BrowserSession+from browser_use.llm import ChatOpenAIif not os.getenv('OPENAI_API_KEY'):raise ValueError('OPENAI_API_KEY is not set. Please add it to your environment variables.')diff --git a/examples/features/custom_output.py b/examples/features/custom_output.pyindex fd33bf56b..165e36901 100644--- a/examples/features/custom_output.py+++ b/examples/features/custom_output.py@@ -14,10 +14,10 @@ from dotenv import load_dotenvload_dotenv()-from langchain_openai import ChatOpenAIfrom pydantic import BaseModelfrom browser_use import Agent, Controller+from browser_use.llm import ChatOpenAIclass Post(BaseModel):diff --git a/examples/features/custom_system_prompt.py b/examples/features/custom_system_prompt.pyindex 306178738..a19af6beb 100644--- a/examples/features/custom_system_prompt.py+++ b/examples/features/custom_system_prompt.py@@ -9,9 +9,8 @@ from dotenv import load_dotenvload_dotenv()-from langchain_openai import ChatOpenAI-from browser_use import Agent+from browser_use.llm import ChatOpenAIextend_system_message = ('REMEMBER the most important RULE: ALWAYS open first a new tab and go first to url wikipedia.com no matter the task!!!'diff --git a/examples/features/custom_user_agent.py b/examples/features/custom_user_agent.pyindex c4cb6d525..9e05abaa6 100644--- a/examples/features/custom_user_agent.py+++ b/examples/features/custom_user_agent.py@@ -9,17 +9,15 @@ from dotenv import load_dotenvload_dotenv()-from langchain_anthropic import ChatAnthropic-from langchain_openai import ChatOpenAI-from browser_use import Agentfrom browser_use.browser import BrowserProfile, BrowserSessionfrom browser_use.controller.service import Controller+from browser_use.llm import ChatAnthropic, ChatOpenAIdef get_llm(provider: str):if provider == 'anthropic':- return ChatAnthropic(model_name='claude-3-5-sonnet-20240620', timeout=25, stop=None, temperature=0.0)+ return ChatAnthropic(model='claude-3-5-sonnet-20240620', temperature=0.0)elif provider == 'openai':return ChatOpenAI(model='gpt-4o', temperature=0.0)diff --git a/examples/features/custom_vector_store.py b/examples/features/custom_vector_store.pydeleted file mode 100644index 77088bbfe..000000000--- a/examples/features/custom_vector_store.py+++ /dev/null@@ -1,180 +0,0 @@-"""-Script that demonstrates how to use the new customizable MemoryConfig with Browser Use, showcasing two different vector store providers:-the default FAISS (local) and a more scalable option like Qdrant-You'll need a Qdrant server running locally to run the Qdrant example.-You can visualize your Qdrant memories at http://localhost:6333/dashboard#/collections-"""--import asyncio-import os--from dotenv import load_dotenv-from langchain_openai import ChatOpenAI--from browser_use import Agent-from browser_use.agent.memory import MemoryConfig--# Load environment variables (e.g., OPENAI_API_KEY)-load_dotenv()--# Ensure OpenAI API key is set-if not os.getenv('OPENAI_API_KEY'):- print('Error: OPENAI_API_KEY environment variable not set.')- exit()---async def run_agent_with_memory_config(- task: str,- llm: ChatOpenAI,- memory_config: MemoryConfig | None,- agent_name: str,- max_steps: int = 5, # Keep low for demo purposes-):- print(f'\n--- Running Agent: {agent_name} ---')- if memory_config:- print(f'Memory Provider: {memory_config.vector_store_provider}')- if memory_config.vector_store_provider != 'memory': # 'memory' provider doesn't use path or collection- print(f'Vector Store Collection: {memory_config.vector_store_config_dict["config"].get("collection_name", "N/A")}')- if memory_config.vector_store_provider in ['faiss', 'chroma']:- print(f'Vector Store Path: {memory_config.vector_store_config_dict["config"].get("path", "N/A")}')-- agent = Agent(- task=task,- llm=llm,- enable_memory=True if memory_config else False, # Enable memory if config is provided- memory_config=memory_config, # Pass the specific memory config- # Set a lower planner_interval for more frequent planning in short demos- # and potentially see memory summarization happen sooner if memory_interval is also low.- planner_interval=2,- )-- print(f'Starting task: {task}')- history = await agent.run(max_steps=max_steps)-- print(f'\n--- {agent_name} Finished ---')- print(f'Task completed: {history.is_done()}')- print(f'Final result/summary: {history.final_result()}')- print(f'Number of steps taken: {len(history.history)}')-- # Let's refine how to access summaries. The summary is added as a 'memory' type message.-- summaries_created = []- for item in agent.message_manager.state.history.get_messages():- # get_messages() returns tuples of (step_number, messages)- if isinstance(item, tuple) and len(item) == 2:- step_number, step_messages = item- if isinstance(step_messages, list):- for msg in step_messages:- if (- hasattr(msg, 'additional_kwargs')- and msg.additional_kwargs.get('metadata', {}).get('message_type') == 'memory'- ):- summaries_created.append(msg.content)- elif (- hasattr(step_messages, 'additional_kwargs')- and step_messages.additional_kwargs.get('metadata', {}).get('message_type') == 'memory'- ):- summaries_created.append(step_messages.content)-- if summaries_created:- print('\nProcedural Summaries Created during run:')- for i, summary in enumerate(summaries_created):- print(f' Summary {i + 1}: {summary[:150]}...') # Print first 150 chars- else:- # Check if messages were consolidated by looking at the agent's final message history- final_messages = agent.message_manager.get_messages()- summaries_in_final_context = [- m.content- for m in final_messages- if hasattr(m, 'additional_kwargs') and m.additional_kwargs.get('message_type') == 'memory'- ]- if summaries_in_final_context:- print('\nProcedural Summaries in final context:')- for i, summary in enumerate(summaries_in_final_context):- print(f' Summary {i + 1}: {summary[:150]}...')- else:- print(- 'No explicit procedural summaries found in final context (task might have been too short or memory interval not reached).'- )-- print('---------------------------\n')- return history---async def main():- """Main function to run the agent with different memory configurations."""- common_task = 'Find the current CEO of OpenAI and then search for news about their latest projects. Summarize your findings.'- shared_agent_id = 'persistent_browser_agent_001' # Use the same ID to test persistence with Qdrant-- # Initialize the LLM (e.g., OpenAI's GPT-4o)- # Ensure your OPENAI_API_KEY is set in your environment or .env file- llm = ChatOpenAI(model='gpt-4o', temperature=0)-- # --- Scenario 1: Default FAISS Memory ---- # MemoryConfig will use its defaults: FAISS, HuggingFace embedder if llm_instance not directly used by Mem0 for defaults- # Since we pass llm_instance, it will likely pick OpenAI embedder- faiss_memory_config = MemoryConfig(- llm_instance=llm, # Crucial for Mem0 to use this LLM for summarization- agent_id=shared_agent_id,- memory_interval=3, # Summarize more frequently for demo- # vector_store_provider is 'faiss' by default- # embedder_provider will default based on llm_instance- )- await run_agent_with_memory_config(common_task, llm, faiss_memory_config, 'Agent with FAISS Memory')-- print('\n === PAUSE: Check FAISS data in /tmp/mem0... (if created) ===\n')- # You might need to adjust the path based on your embedder_dims, e.g., /tmp/mem0_1536_faiss- input('Press Enter to continue to Qdrant example...')-- # --- Scenario 2: Qdrant Memory ---- # Ensure Qdrant server is running (e.g., `docker run -p 6333:6333 qdrant/qdrant`)- print('Attempting to use Qdrant. Make sure Qdrant server is running on localhost:6333.')- try:- qdrant_memory_config = MemoryConfig(- llm_instance=llm, # Pass the LLM for Mem0's internal use- agent_id=shared_agent_id, # Same agent_id for potential persistence- memory_interval=3, # Summarize more frequently- embedder_provider='openai', # Explicitly set for consistency- embedder_model='text-embedding-3-small',- embedder_dims=1536,- vector_store_provider='qdrant',- vector_store_collection_name='browser_use_qdrant_demo', # Custom collection name- vector_store_config_override={- 'host': 'localhost',- 'port': 6333,- # For Qdrant Cloud, you'd add "api_key": "YOUR_QDRANT_CLOUD_KEY", "url": "YOUR_QDRANT_CLOUD_URL"- # "path": ":memory:" # For in-memory Qdrant, useful for quick tests without persistence- },- )- await run_agent_with_memory_config(- common_task, # Could be a follow-up task to test memory persistence- llm,- qdrant_memory_config,- 'Agent with Qdrant Memory',- )- except ImportError as e:- print(f'Could not run Qdrant example due to missing dependency: {e}')- print('Please install qdrant-client: pip install qdrant-client')- except Exception as e:- print(f'Error running Qdrant agent: {e}')- print('Ensure Qdrant server is running and accessible.')-- # --- Scenario 3: No Memory (for comparison) ---- # await run_agent_with_memory_config(- # common_task,- # llm,- # None, # Pass None for memory_config to disable memory- # "Agent with NO Memory"- # )---if __name__ == '__main__':- import sys-- if sys.platform.startswith('win'):- # WindowsProactorEventLoopPolicy is only available on Windows- try:- asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy()) # type: ignore- except AttributeError:- pass # Not on Windows, ignore- asyncio.run(main())diff --git a/examples/features/download_file.py b/examples/features/download_file.pyindex 1c2b03c86..49ddfdc1c 100644--- a/examples/features/download_file.py+++ b/examples/features/download_file.py@@ -8,18 +8,17 @@ from dotenv import load_dotenvload_dotenv()-from langchain_google_genai import ChatGoogleGenerativeAI-from pydantic import SecretStrfrom browser_use import Agentfrom browser_use.browser import BrowserSession+from browser_use.llm import ChatGoogleapi_key = os.getenv('GOOGLE_API_KEY')if not api_key:raise ValueError('GOOGLE_API_KEY is not set')assert api_key is not None, 'GOOGLE_API_KEY must be set'-llm = ChatGoogleGenerativeAI(model='gemini-2.0-flash-exp', api_key=SecretStr(api_key))+llm = ChatGoogle(model='gemini-2.0-flash-exp', api_key=api_key)from browser_use.browser import BrowserProfilediff --git a/examples/features/drag_drop.py b/examples/features/drag_drop.pyindex e2c7a4d48..c5f920cdb 100644--- a/examples/features/drag_drop.py+++ b/examples/features/drag_drop.py@@ -8,16 +8,16 @@ from dotenv import load_dotenvload_dotenv()-from langchain_google_genai import ChatGoogleGenerativeAI-from pydantic import SecretStrfrom browser_use import Agent+from browser_use.llm import ChatGoogleapi_key = os.getenv('GOOGLE_API_KEY')if not api_key:raise ValueError('GOOGLE_API_KEY is not set')-llm = ChatGoogleGenerativeAI(model='gemini-2.0-flash-exp', api_key=SecretStr(api_key))+# API key is automatically set from the environment variable GOOGLE_API_KEY+llm = ChatGoogle(model='gemini-2.0-flash-exp')task_1 = """diff --git a/examples/features/follow_up_tasks.py b/examples/features/follow_up_tasks.pyindex 053227e8c..93f448207 100644--- a/examples/features/follow_up_tasks.py+++ b/examples/features/follow_up_tasks.py@@ -8,10 +8,9 @@ from dotenv import load_dotenvload_dotenv()-from langchain_openai import ChatOpenAI-from browser_use import Agent, Controllerfrom browser_use.browser import BrowserProfile, BrowserSession+from browser_use.llm import ChatOpenAI# Initialize the modelllm = ChatOpenAI(diff --git a/examples/features/initial_actions.py b/examples/features/initial_actions.pyindex bd74d7145..adc0cfe50 100644--- a/examples/features/initial_actions.py+++ b/examples/features/initial_actions.py@@ -8,9 +8,8 @@ from dotenv import load_dotenvload_dotenv()-from langchain_openai import ChatOpenAI-from browser_use import Agent+from browser_use.llm import ChatOpenAIllm = ChatOpenAI(model='gpt-4o')diff --git a/examples/features/multi-tab_handling.py b/examples/features/multi-tab_handling.pyindex 779b28c1d..fa4d38447 100644--- a/examples/features/multi-tab_handling.py+++ b/examples/features/multi-tab_handling.py@@ -14,9 +14,8 @@ from dotenv import load_dotenvload_dotenv()-from langchain_openai import ChatOpenAI-from browser_use import Agent+from browser_use.llm import ChatOpenAI# video: https://preview.screen.studio/share/clenCmS6llm = ChatOpenAI(model='gpt-4o')diff --git a/examples/features/multiple_tasks.py b/examples/features/multiple_tasks.pyindex b2de96126..9ccacf188 100644--- a/examples/features/multiple_tasks.py+++ b/examples/features/multiple_tasks.py@@ -8,19 +8,18 @@ from dotenv import load_dotenvload_dotenv()-from langchain_google_genai import ChatGoogleGenerativeAI-from pydantic import SecretStrfrom browser_use import Agentfrom browser_use.browser import BrowserSessionfrom browser_use.browser.types import async_playwright+from browser_use.llm import ChatGoogleapi_key = os.getenv('GOOGLE_API_KEY')if not api_key:raise ValueError('GOOGLE_API_KEY is not set')-llm = ChatGoogleGenerativeAI(model='gemini-2.0-flash', api_key=SecretStr(api_key))+llm = ChatGoogle(model='gemini-2.0-flash', api_key=api_key)async def main():diff --git a/examples/features/outsource_state.py b/examples/features/outsource_state.pyindex d1936c50a..821d84250 100644--- a/examples/features/outsource_state.py+++ b/examples/features/outsource_state.py@@ -15,11 +15,11 @@ from dotenv import load_dotenvload_dotenv()import anyio-from langchain_openai import ChatOpenAIfrom browser_use import Agentfrom browser_use.agent.views import AgentStatefrom browser_use.browser import BrowserProfile, BrowserSession+from browser_use.llm import ChatOpenAIasync def main():diff --git a/examples/features/parallel_agents.py b/examples/features/parallel_agents.pyindex 0912a30fa..39e957fbc 100644--- a/examples/features/parallel_agents.py+++ b/examples/features/parallel_agents.py@@ -8,10 +8,9 @@ from dotenv import load_dotenvload_dotenv()-from langchain_openai import ChatOpenAI-from browser_use.agent.service import Agentfrom browser_use.browser import BrowserProfile, BrowserSession+from browser_use.llm import ChatOpenAIbrowser_session = BrowserSession(browser_profile=BrowserProfile(diff --git a/examples/features/pause_agent.py b/examples/features/pause_agent.pyindex 359e04702..cced99efc 100644--- a/examples/features/pause_agent.py+++ b/examples/features/pause_agent.py@@ -9,9 +9,8 @@ from dotenv import load_dotenvload_dotenv()-from langchain_openai import ChatOpenAI-from browser_use import Agent+from browser_use.llm import ChatOpenAIclass AgentController:diff --git a/examples/features/planner.py b/examples/features/planner.pyindex 00d56b40a..e528a81a2 100644--- a/examples/features/planner.py+++ b/examples/features/planner.py@@ -8,9 +8,8 @@ from dotenv import load_dotenvload_dotenv()-from langchain_openai import ChatOpenAI-from browser_use import Agent+from browser_use.llm import ChatOpenAIllm = ChatOpenAI(model='gpt-4o', temperature=0.0)planner_llm = ChatOpenAI(diff --git a/examples/features/restrict_urls.py b/examples/features/restrict_urls.pyindex f131456b0..6383793b8 100644--- a/examples/features/restrict_urls.py+++ b/examples/features/restrict_urls.py@@ -8,10 +8,9 @@ from dotenv import load_dotenvload_dotenv()-from langchain_openai import ChatOpenAI-from browser_use import Agentfrom browser_use.browser import BrowserProfile, BrowserSession+from browser_use.llm import ChatOpenAIllm = ChatOpenAI(model='gpt-4o', temperature=0.0)task = (diff --git a/examples/features/result_processing.py b/examples/features/result_processing.pyindex 38c12847b..6030c6083 100644--- a/examples/features/result_processing.py+++ b/examples/features/result_processing.py@@ -9,11 +9,10 @@ from dotenv import load_dotenvload_dotenv()-from langchain_openai import ChatOpenAI-from browser_use import Agentfrom browser_use.agent.views import AgentHistoryListfrom browser_use.browser import BrowserProfile, BrowserSession+from browser_use.llm import ChatOpenAIllm = ChatOpenAI(model='gpt-4o')diff --git a/examples/features/save_trace.py b/examples/features/save_trace.pyindex b0701fd07..6e93fb2ee 100644--- a/examples/features/save_trace.py+++ b/examples/features/save_trace.py@@ -8,10 +8,9 @@ from dotenv import load_dotenvload_dotenv()-from langchain_openai import ChatOpenAI-from browser_use.agent.service import Agentfrom browser_use.browser import BrowserProfile, BrowserSession+from browser_use.llm import ChatOpenAIllm = ChatOpenAI(model='gpt-4o', temperature=0.0)diff --git a/examples/features/sensitive_data.py b/examples/features/sensitive_data.pyindex c38be553c..33206cc7b 100644--- a/examples/features/sensitive_data.py+++ b/examples/features/sensitive_data.py@@ -8,10 +8,9 @@ from dotenv import load_dotenvload_dotenv()-from langchain_openai import ChatOpenAI-from browser_use import Agentfrom browser_use.browser import BrowserProfile+from browser_use.llm import ChatOpenAI# Initialize the modelllm = ChatOpenAI(diff --git a/examples/features/small_model_for_extraction.py b/examples/features/small_model_for_extraction.pyindex c0507abdb..f0c1335bd 100644--- a/examples/features/small_model_for_extraction.py+++ b/examples/features/small_model_for_extraction.py@@ -8,9 +8,8 @@ from dotenv import load_dotenvload_dotenv()-from langchain_openai import ChatOpenAI-from browser_use import Agent+from browser_use.llm import ChatOpenAIllm = ChatOpenAI(model='gpt-4o', temperature=0.0)small_llm = ChatOpenAI(model='gpt-4o-mini', temperature=0.0)diff --git a/examples/features/task_with_memory.py b/examples/features/task_with_memory.pydeleted file mode 100644index 746d3f259..000000000--- a/examples/features/task_with_memory.py+++ /dev/null@@ -1,103 +0,0 @@-import asyncio-import json-import os-import sys--sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))--from dotenv import load_dotenv--load_dotenv()--import anyio-from langchain_openai import ChatOpenAI-from pydantic import BaseModel--from browser_use import Agent, Controller-from browser_use.browser import BrowserProfile, BrowserSession--links = [- 'https://docs.mem0.ai/components/llms/models/litellm',- 'https://docs.mem0.ai/components/llms/models/mistral_AI',- 'https://docs.mem0.ai/components/llms/models/ollama',- 'https://docs.mem0.ai/components/llms/models/openai',- 'https://docs.mem0.ai/components/llms/models/together',- 'https://docs.mem0.ai/components/llms/models/xAI',- 'https://docs.mem0.ai/components/llms/overview',- 'https://docs.mem0.ai/components/vectordbs/config',- 'https://docs.mem0.ai/components/vectordbs/dbs/azure_ai_search',- 'https://docs.mem0.ai/components/vectordbs/dbs/chroma',- 'https://docs.mem0.ai/components/vectordbs/dbs/elasticsearch',- 'https://docs.mem0.ai/components/vectordbs/dbs/milvus',- 'https://docs.mem0.ai/components/vectordbs/dbs/opensearch',- 'https://docs.mem0.ai/components/vectordbs/dbs/pgvector',- 'https://docs.mem0.ai/components/vectordbs/dbs/pinecone',- 'https://docs.mem0.ai/components/vectordbs/dbs/qdrant',- 'https://docs.mem0.ai/components/vectordbs/dbs/redis',- 'https://docs.mem0.ai/components/vectordbs/dbs/supabase',- 'https://docs.mem0.ai/components/vectordbs/dbs/vertex_ai_vector_search',- 'https://docs.mem0.ai/components/vectordbs/dbs/weaviate',- 'https://docs.mem0.ai/components/vectordbs/overview',- 'https://docs.mem0.ai/contributing/development',- 'https://docs.mem0.ai/contributing/documentation',- 'https://docs.mem0.ai/core-concepts/memory-operations',- 'https://docs.mem0.ai/core-concepts/memory-types',-]---class Link(BaseModel):- url: str- title: str- summary: str---class Links(BaseModel):- links: list[Link]---initial_actions = [- {'open_tab': {'url': 'https://docs.mem0.ai/'}},-]-controller = Controller(output_model=Links)-task_description = f"""-Visit all the links provided in {links} and summarize the content of the page with url and title. There are {len(links)} links to visit. Make sure to visit all the links. Return a json with the following format: [{{url: <url>, title: <title>, summary: <summary>}}].--Guidelines:-1. Strictly stay on the domain https://docs.mem0.ai-2. Do not visit any other websites.-3. Ignore the links that are hashed (#) or javascript (:), or mailto, or tel, or other protocols-4. Don't visit any other url other than the ones provided above.-5. Capture the unique urls which are not already visited.-6. If you visit any page that doesn't have host name docs.mem0.ai, then do not visit it and come back to the page with host name docs.mem0.ai.-"""---async def main(max_steps=500):- browser_profile = BrowserProfile(headless=True)- browser_session = BrowserSession(browser_profile=browser_profile)-- agent = Agent(- task=task_description,- llm=ChatOpenAI(model='gpt-4o-mini'),- controller=controller,- initial_actions=initial_actions,- enable_memory=True,- browser_session=browser_session,- )- history = await agent.run(max_steps=max_steps)- result = history.final_result()- parsed_result = []- if result:- parsed: Links = Links.model_validate_json(result)- print(f'Total parsed links: {len(parsed.links)}')- for link in parsed.links:- parsed_result.append({'title': link.title, 'url': link.url, 'summary': link.summary})- else:- print('No result')-- async with await anyio.open_file('result.json', 'w+') as f:- await f.write(json.dumps(parsed_result, indent=4))---if __name__ == '__main__':- asyncio.run(main())diff --git a/examples/features/validate_output.py b/examples/features/validate_output.pyindex 889769d4c..c3bd5b558 100644--- a/examples/features/validate_output.py+++ b/examples/features/validate_output.py@@ -14,10 +14,10 @@ from dotenv import load_dotenvload_dotenv()-from langchain_openai import ChatOpenAIfrom pydantic import BaseModelfrom browser_use import ActionResult, Agent, Controller+from browser_use.llm import ChatOpenAIcontroller = Controller()diff --git a/examples/integrations/discord/discord_api.py b/examples/integrations/discord/discord_api.pyindex ba9484a2d..0353ace42 100644--- a/examples/integrations/discord/discord_api.py+++ b/examples/integrations/discord/discord_api.py@@ -9,10 +9,10 @@ load_dotenv()import discord # type: ignorefrom discord.ext import commands # type: ignore-from langchain_core.language_models.chat_models import BaseChatModelfrom browser_use.agent.service import Agentfrom browser_use.browser import BrowserProfile, BrowserSession+from browser_use.llm import BaseChatModelclass DiscordBot(commands.Bot):@@ -31,7 +31,7 @@ class DiscordBot(commands.Bot):Usage:```python- from langchain_openai import ChatOpenAI+ from browser_use.llm import ChatOpenAIllm = ChatOpenAI()bot = DiscordBot(llm=llm, prefix='$bu', ack=True)diff --git a/examples/integrations/discord/discord_example.py b/examples/integrations/discord/discord_example.pyindex 6c9f61891..b87df1c93 100644--- a/examples/integrations/discord/discord_example.py+++ b/examples/integrations/discord/discord_example.py@@ -41,10 +41,9 @@ from dotenv import load_dotenvload_dotenv()-from langchain_google_genai import ChatGoogleGenerativeAI-from pydantic import SecretStrfrom browser_use.browser import BrowserProfile+from browser_use.llm import ChatGooglefrom examples.integrations.discord.discord_api import DiscordBot# load credentials from environment variables@@ -56,7 +55,7 @@ api_key = os.getenv('GOOGLE_API_KEY')if not api_key:raise ValueError('GOOGLE_API_KEY is not set')-llm = ChatGoogleGenerativeAI(model='gemini-2.0-flash-exp', api_key=SecretStr(api_key))+llm = ChatGoogle(model='gemini-2.0-flash-exp', api_key=api_key)bot = DiscordBot(llm=llm, # required; instance of BaseChatModeldiff --git a/examples/integrations/slack/slack_api.py b/examples/integrations/slack/slack_api.pyindex 68cc1f7a4..a181fbd1e 100644--- a/examples/integrations/slack/slack_api.py+++ b/examples/integrations/slack/slack_api.py@@ -10,13 +10,13 @@ from dotenv import load_dotenvload_dotenv()from fastapi import Depends, FastAPI, HTTPException, Request-from langchain_core.language_models.chat_models import BaseChatModelfrom slack_sdk.errors import SlackApiError # type: ignorefrom slack_sdk.signature import SignatureVerifier # type: ignorefrom slack_sdk.web.async_client import AsyncWebClient # type: ignorefrom browser_use.agent.service import Agentfrom browser_use.browser import BrowserProfile, BrowserSession+from browser_use.llm import BaseChatModelfrom browser_use.logging_config import setup_loggingsetup_logging()diff --git a/examples/integrations/slack/slack_example.py b/examples/integrations/slack/slack_example.pyindex 0c7a40f56..1c62064d0 100644--- a/examples/integrations/slack/slack_example.py+++ b/examples/integrations/slack/slack_example.py@@ -7,10 +7,9 @@ from dotenv import load_dotenvload_dotenv()-from langchain_google_genai import ChatGoogleGenerativeAI-from pydantic import SecretStrfrom browser_use.browser import BrowserProfile+from browser_use.llm import ChatGooglefrom examples.integrations.slack.slack_api import SlackBot, app# load credentials from environment variables@@ -26,7 +25,7 @@ api_key = os.getenv('GOOGLE_API_KEY')if not api_key:raise ValueError('GOOGLE_API_KEY is not set')-llm = ChatGoogleGenerativeAI(model='gemini-2.0-flash-exp', api_key=SecretStr(api_key))+llm = ChatGoogle(model='gemini-2.0-flash-exp', api_key=api_key)slack_bot = SlackBot(llm=llm, # required; instance of BaseChatModeldiff --git a/examples/models/_ollama.py b/examples/models/_ollama.pydeleted file mode 100644index 122859ec0..000000000--- a/examples/models/_ollama.py+++ /dev/null@@ -1,42 +0,0 @@-# Optional: Disable telemetry-# os.environ["ANONYMIZED_TELEMETRY"] = "false"--# Optional: Set the OLLAMA host to a remote server-# os.environ["OLLAMA_HOST"] = "http://x.x.x.x:11434"--import asyncio-import os-import sys--sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))--from dotenv import load_dotenv--load_dotenv()--from langchain_ollama import ChatOllama--from browser_use import Agent-from browser_use.agent.views import AgentHistoryList---async def run_search() -> AgentHistoryList:- agent = Agent(- task="Search for a 'browser use' post on the r/LocalLLaMA subreddit and open it.",- llm=ChatOllama(- model='qwen2.5:32b-instruct-q4_K_M',- num_ctx=32000,- ),- )-- result = await agent.run()- return result---async def main():- result = await run_search()- print('\n\n', result)---if __name__ == '__main__':- asyncio.run(main())diff --git a/examples/models/azure_openai.py b/examples/models/azure_openai.pyindex cb260997f..168e547fd 100644--- a/examples/models/azure_openai.py+++ b/examples/models/azure_openai.py@@ -14,10 +14,9 @@ from dotenv import load_dotenvload_dotenv()-from langchain_openai import AzureChatOpenAI-from pydantic import SecretStrfrom browser_use import Agent+from browser_use.llm import ChatAzureOpenAI# Retrieve Azure-specific environment variablesazure_openai_api_key = os.getenv('AZURE_OPENAI_KEY')@@ -27,11 +26,10 @@ if not azure_openai_api_key or not azure_openai_endpoint:raise ValueError('AZURE_OPENAI_KEY or AZURE_OPENAI_ENDPOINT is not set')# Initialize the Azure OpenAI client-llm = AzureChatOpenAI(+llm = ChatAzureOpenAI(model='gpt-4o',- api_key=SecretStr(azure_openai_api_key) if azure_openai_api_key else None,+ api_key=azure_openai_api_key,azure_endpoint=azure_openai_endpoint, # Corrected to use azure_endpoint instead of openai_api_base- api_version='2024-08-01-preview', # Explicitly set the API version here)agent = Agent(diff --git a/examples/models/bedrock_claude.py b/examples/models/bedrock_claude.pydeleted file mode 100644index 2e5ef44f7..000000000--- a/examples/models/bedrock_claude.py+++ /dev/null@@ -1,75 +0,0 @@-# pyright: reportMissingImports=false-"""-Automated news analysis and sentiment scoring using Bedrock.--Ensure you have browser-use installed with `examples` extra, i.e. `uv install 'browser-use[examples]'`--@dev Ensure AWS environment variables are set correctly for Bedrock access.-"""--import argparse-import asyncio-import os-import sys--sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))--from dotenv import load_dotenv--load_dotenv()--import boto3 # type: ignore-from botocore.config import Config-from langchain_aws import ChatBedrockConverse # type: ignore--from browser_use import Agent-from browser_use.browser import BrowserProfile, BrowserSession-from browser_use.controller.service import Controller---def get_llm():- config = Config(retries={'max_attempts': 10, 'mode': 'adaptive'})- bedrock_client = boto3.client('bedrock-runtime', region_name='us-east-1', config=config)-- return ChatBedrockConverse(- model_id='us.anthropic.claude-3-5-sonnet-20241022-v2:0',- temperature=0.0,- max_tokens=None,- client=bedrock_client,- )---# Define the task for the agent-task = (- "Visit cnn.com, navigate to the 'World News' section, and identify the latest headline. "- 'Open the first article and summarize its content in 3-4 sentences. '- 'Additionally, analyze the sentiment of the article (positive, neutral, or negative) '- 'and provide a confidence score for the sentiment. Present the result in a tabular format.'-)--parser = argparse.ArgumentParser()-parser.add_argument('--query', type=str, help='The query for the agent to execute', default=task)-args = parser.parse_args()--llm = get_llm()--browser_profile = BrowserProfile(- # executable_path='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',-)-browser_session = BrowserSession(browser_profile=browser_profile)--agent = Agent(- task=args.query,- llm=llm,- controller=Controller(),- browser_session=browser_session,- validate_output=True,-)---async def main():- await agent.run(max_steps=30)- await browser_session.close()---asyncio.run(main())diff --git a/examples/models/claude-3.7-sonnet.py b/examples/models/claude-3.7-sonnet.pyindex ca56499f8..7170b7abc 100644--- a/examples/models/claude-3.7-sonnet.py+++ b/examples/models/claude-3.7-sonnet.py@@ -13,11 +13,10 @@ from dotenv import load_dotenvload_dotenv()-from langchain_anthropic import ChatAnthropic-from browser_use import Agent+from browser_use.llm import ChatAnthropic-llm = ChatAnthropic(model_name='claude-3-7-sonnet-20250219', temperature=0.0, timeout=30, stop=None)+llm = ChatAnthropic(model='claude-3-7-sonnet-20250219', temperature=0.0)agent = Agent(task='Go to amazon.com, search for laptop, sort by best rating, and give me the price of the first result',diff --git a/examples/models/deepseek-r1.py b/examples/models/deepseek-r1.pydeleted file mode 100644index 57dba135f..000000000--- a/examples/models/deepseek-r1.py+++ /dev/null@@ -1,38 +0,0 @@-import asyncio-import os-import sys--sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))--from dotenv import load_dotenv--load_dotenv()--from langchain_deepseek import ChatDeepSeek-from pydantic import SecretStr--from browser_use import Agent--api_key = os.getenv('DEEPSEEK_API_KEY', '')-if not api_key:- raise ValueError('DEEPSEEK_API_KEY is not set')---async def run_search():- agent = Agent(- task=('go to amazon.com, search for laptop, sort by best rating, and give me the price of the first result'),- llm=ChatDeepSeek(- base_url='https://api.deepseek.com/v1',- model='deepseek-reasoner',- api_key=SecretStr(api_key),- ),- use_vision=False,- max_failures=2,- max_actions_per_step=1,- )-- await agent.run()---if __name__ == '__main__':- asyncio.run(run_search())diff --git a/examples/models/deepseek.py b/examples/models/deepseek.pydeleted file mode 100644index bbea27570..000000000--- a/examples/models/deepseek.py+++ /dev/null@@ -1,41 +0,0 @@-import asyncio-import os-import sys--sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))--from dotenv import load_dotenv--load_dotenv()--from langchain_deepseek import ChatDeepSeek-from pydantic import SecretStr--from browser_use import Agent--api_key = os.getenv('DEEPSEEK_API_KEY', '')-if not api_key:- raise ValueError('DEEPSEEK_API_KEY is not set')---async def run_search():- agent = Agent(- task=(- '1. Go to https://www.reddit.com/r/LocalLLaMA '- "2. Search for 'browser use' in the search bar"- '3. Click on first result'- '4. Return the first comment'- ),- llm=ChatDeepSeek(- base_url='https://api.deepseek.com/v1',- model='deepseek-chat',- api_key=SecretStr(api_key),- ),- use_vision=False,- )-- await agent.run()---if __name__ == '__main__':- asyncio.run(run_search())diff --git a/examples/models/gemini.py b/examples/models/gemini.pyindex cc6fe77cc..aa8941b50 100644--- a/examples/models/gemini.py+++ b/examples/models/gemini.py@@ -8,17 +8,16 @@ from dotenv import load_dotenvload_dotenv()-from langchain_google_genai import ChatGoogleGenerativeAI-from pydantic import SecretStrfrom browser_use import Agentfrom browser_use.browser import BrowserProfile, BrowserSession+from browser_use.llm import ChatGoogleapi_key = os.getenv('GOOGLE_API_KEY')if not api_key:raise ValueError('GOOGLE_API_KEY is not set')-llm = ChatGoogleGenerativeAI(model='gemini-2.0-flash-exp', api_key=SecretStr(api_key))+llm = ChatGoogle(model='gemini-2.0-flash-exp', api_key=api_key)browser_session = BrowserSession(browser_profile=BrowserProfile(diff --git a/examples/models/gpt-4o.py b/examples/models/gpt-4.1.pysimilarity index 77%rename from examples/models/gpt-4o.pyrename to examples/models/gpt-4.1.pyindex 8fdfa5253..9c4106abc 100644--- a/examples/models/gpt-4o.py+++ b/examples/models/gpt-4.1.py@@ -14,11 +14,11 @@ from dotenv import load_dotenvload_dotenv()-from langchain_openai import ChatOpenAI-from browser_use import Agent+from browser_use.llm import ChatOpenAI-llm = ChatOpenAI(model='gpt-4o')+# All the models are type safe from OpenAI in case you need a list of supported models+llm = ChatOpenAI(model='gpt-4.1')agent = Agent(task='Go to amazon.com, search for laptop, sort by best rating, and give me the price of the first result',llm=llm,diff --git a/examples/models/grok.py b/examples/models/grok.pydeleted file mode 100644index 313626669..000000000--- a/examples/models/grok.py+++ /dev/null@@ -1,41 +0,0 @@-import asyncio-import os-import sys--sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))--from dotenv import load_dotenv--load_dotenv()--from langchain_openai import ChatOpenAI-from pydantic import SecretStr--from browser_use import Agent--api_key = os.getenv('GROK_API_KEY', '')-if not api_key:- raise ValueError('GROK_API_KEY is not set')---async def run_search():- agent = Agent(- task=(- '1. Go to https://www.amazon.com'- '2. Search for "wireless headphones"'- '3. Filter by "Highest customer rating"'- '4. Return the title and price of the first product'- ),- llm=ChatOpenAI(- base_url='https://api.x.ai/v1',- model='grok-3-beta',- api_key=SecretStr(api_key),- ),- use_vision=False,- )-- await agent.run()---if __name__ == '__main__':- asyncio.run(run_search())diff --git a/examples/models/llama4-groq.py b/examples/models/llama4-groq.pyindex a6bbe6095..6546bdd5a 100644--- a/examples/models/llama4-groq.py+++ b/examples/models/llama4-groq.py@@ -8,16 +8,13 @@ from dotenv import load_dotenvload_dotenv()-from langchain_openai import ChatOpenAI-from pydantic import SecretStrfrom browser_use import Agent+from browser_use.llm import ChatGroqgroq_api_key = os.environ.get('GROQ_API_KEY')-llm = ChatOpenAI(+llm = ChatGroq(model='meta-llama/llama-4-maverick-17b-128e-instruct',- base_url='https://api.groq.com/openai/v1',- api_key=SecretStr(groq_api_key) if groq_api_key else None,temperature=0.0,)diff --git a/examples/models/novita.py b/examples/models/novita.pyindex ac2c424bb..46e2dd3e2 100644--- a/examples/models/novita.py+++ b/examples/models/novita.py@@ -14,10 +14,9 @@ from dotenv import load_dotenvload_dotenv()-from langchain_openai import ChatOpenAI-from pydantic import SecretStrfrom browser_use import Agent+from browser_use.llm import ChatOpenAIapi_key = os.getenv('NOVITA_API_KEY', '')if not api_key:@@ -35,7 +34,7 @@ async def run_search():llm=ChatOpenAI(base_url='https://api.novita.ai/v3/openai',model='deepseek/deepseek-v3-0324',- api_key=SecretStr(api_key),+ api_key=api_key,),use_vision=False,)diff --git a/examples/models/qwen.py b/examples/models/qwen.pydeleted file mode 100644index 3f8ba380b..000000000--- a/examples/models/qwen.py+++ /dev/null@@ -1,34 +0,0 @@-import asyncio-import os-import sys--sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))--from dotenv import load_dotenv--load_dotenv()--from langchain_ollama import ChatOllama--from browser_use import Agent---async def run_search():- agent = Agent(- task=(- "1. Go to https://www.reddit.com/r/LocalLLaMA2. Search for 'browser use' in the search bar3. Click search4. Call done"- ),- llm=ChatOllama(- # model='qwen2.5:32b-instruct-q4_K_M',- # model='qwen2.5:14b',- model='qwen2.5:latest',- num_ctx=128000,- ),- max_actions_per_step=1,- )-- await agent.run()---if __name__ == '__main__':- asyncio.run(run_search())diff --git a/examples/notebook/agent_browsing.ipynb b/examples/notebook/agent_browsing.ipynbdeleted file mode 100644index a1596b77e..000000000--- a/examples/notebook/agent_browsing.ipynb+++ /dev/null@@ -1,241 +0,0 @@-{- "cells": [- {- "cell_type": "code",- "execution_count": 2,- "metadata": {- "id": "ZRGlUb8O4fPV"- },- "outputs": [],- "source": [- "%pip install -U langgraph langchain_google_genai langchain_community langgraph-checkpoint-postgres openai langchain_groq"- ]- },- {- "cell_type": "code",- "execution_count": 3,- "metadata": {- "id": "cMfPUmHIxqTi"- },- "outputs": [],- "source": [- "%%capture --no-stderr\n",- "%pip install --upgrade --quiet playwright > /dev/null\n",- "%pip install --upgrade --quiet lxml browser-use langchain_openai"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {- "id": "kkZ7jVUOUV7Q"- },- "outputs": [],- "source": [- "!playwright install"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {- "id": "-_T1MhnGUl2q"- },- "outputs": [],- "source": [- "!pip install \"anyio<4\""- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {- "id": "yARYirp1UhDR"- },- "outputs": [],- "source": [- "# This import is required only for jupyter notebooks, since they have their own eventloop\n",- "import nest_asyncio\n",- "\n",- "nest_asyncio.apply()"- ]- },- {- "cell_type": "code",- "execution_count": 4,- "metadata": {- "id": "jyVP10O_5Qck"- },- "outputs": [],- "source": [- "from google.colab import userdata\n",- "from langchain_openai import ChatOpenAI\n",- "\n",- "llm = ChatOpenAI(model='gpt-4o-mini', temperature=0, api_key=userdata.get('Open_api_key'))"- ]- },- {- "cell_type": "code",- "execution_count": 5,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "id": "e9duizdv5cOH",- "outputId": "a07b1702-d485-4641-c307-601e6ab34b9b"- },- "outputs": [- {- "data": {- "text/plain": [- "AIMessage(content='Hello! How can I assist you today?', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 10, 'prompt_tokens': 8, 'total_tokens': 18, 'completion_tokens_details': {'accepted_prediction_tokens': 0, 'audio_tokens': 0, 'reasoning_tokens': 0, 'rejected_prediction_tokens': 0}, 'prompt_tokens_details': {'audio_tokens': 0, 'cached_tokens': 0}}, 'model_name': 'gpt-4o-mini-2024-07-18', 'system_fingerprint': 'fp_bd83329f63', 'finish_reason': 'stop', 'logprobs': None}, id='run-28a9088f-7539-412a-aa80-1663be40e74f-0', usage_metadata={'input_tokens': 8, 'output_tokens': 10, 'total_tokens': 18, 'input_token_details': {'audio': 0, 'cache_read': 0}, 'output_token_details': {'audio': 0, 'reasoning': 0}})"- ]- },- "execution_count": 5,- "metadata": {},- "output_type": "execute_result"- }- ],- "source": [- "llm.invoke('hi')"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "id": "wS8ouhiVQ2dL",- "outputId": "653879a8-b3ac-4178-edee-5cd834e3404a"- },- "outputs": [],- "source": [- "import asyncio\n",- "\n",- "from langchain_openai import ChatOpenAI\n",- "\n",- "from browser_use import Agent\n",- "from browser_use.browser import BrowserProfile, BrowserSession\n",- "\n",- "# Basic configuration for the browser\n",- "browser_profile = BrowserProfile(\n",- "\theadless=True, # Run in headless mode\n",- "\t# disable_security=True # Uncomment if you want to disable security\n",- ")\n",- "\n",- "# Initialize the browser session with the specified profile\n",- "browser_session = BrowserSession(browser_profile=browser_profile)\n",- "\n",- "\n",- "async def main():\n",- "\t# Initialize the agent with the task and language model\n",- "\tagent = Agent(\n",- "\t\ttask='What is Langgraph',\n",- "\t\tllm=llm, # Replace with your LLM configuration\n",- "\t\tbrowser_session=browser_session,\n",- "\t\tgenerate_gif=False, # Disable GIF generation\n",- "\t)\n",- "\n",- "\t# Run the agent and get results asynchronously\n",- "\tresult = await agent.run()\n",- "\n",- "\t# Process results token-wise\n",- "\tfor action in result.action_results():\n",- "\t\tprint(action.extracted_content, end='\\r', flush=True)\n",- "\t\tprint('\\n\\n')\n",- "\t\t# if action.is_done:\n",- "\t\t# print(action.extracted_content)\n",- "\n",- "\t# Close the browser after completion\n",- "\tawait browser_session.close()\n",- "\n",- "\n",- "# Run the asynchronous main function\n",- "asyncio.run(main())"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "id": "TFK-fNoLDFcF",- "outputId": "d78fbeae-c8f0-4c26-e0e3-7a0a683d3fc1"- },- "outputs": [],- "source": [- "# from browser_use import Agent\n",- "import asyncio\n",- "\n",- "from langchain_openai import ChatOpenAI\n",- "\n",- "from browser_use.browser import BrowserProfile, BrowserSession\n",- "\n",- "# Basic configuration\n",- "browser_profile = BrowserProfile(\n",- "\theadless=True,\n",- "\t# disable_security=True\n",- ")\n",- "# Reuse existing browser\n",- "browser_session = BrowserSession(browser_profile=browser_profile)\n",- "# async def main():\n",- "agent = Agent(\n",- "\ttask='what is langchain',\n",- "\tllm=llm,\n",- "\tbrowser_session=browser_session,\n",- "\tgenerate_gif=False, # Browser instance will be reused\n",- ")\n",- "\n",- "result = await agent.run()\n",- "print(result)\n",- "# Manually close the browser\n",- "# asyncio.run(main())\n",- "await browser_session.close()"- ]- },- {- "cell_type": "code",- "execution_count": 27,- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "id": "nKGC936xODry",- "outputId": "de70d715-c30a-4d5b-9d25-40bd79d410de"- },- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "LangChain is a composable framework designed for building applications with large language models (LLMs). It simplifies the integration of language models with external data sources and is open-source, supported by an active community. LangChain provides tools for developers to streamline the application lifecycle of LLMs.\n"- ]- }- ],- "source": [- "# display(result.action_results())\n",- "for action in result.action_results():\n",- "\tif action.is_done:\n",- "\t\tprint(action.extracted_content)"- ]- }- ],- "metadata": {- "colab": {- "provenance": []- },- "kernelspec": {- "display_name": "Python 3",- "name": "python3"- },- "language_info": {- "name": "python"- }- },- "nbformat": 4,- "nbformat_minor": 0-}diff --git a/examples/simple.py b/examples/simple.pyindex c42bd1dda..7c53263e7 100644--- a/examples/simple.py+++ b/examples/simple.py@@ -2,22 +2,24 @@ import asyncioimport osimport sys+from browser_use.llm.openai.chat import ChatOpenAI+sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))from dotenv import load_dotenvload_dotenv()-from langchain_openai import ChatOpenAIfrom browser_use import Agent# Initialize the modelllm = ChatOpenAI(- model='gpt-4o',- temperature=0.0,+ model='gpt-4.1-mini',)-task = 'Go to kayak.com and find the cheapest one-way flight from Zurich to San Francisco in 3 weeks.'+++task = 'Go to google.com/travel/flights and find the cheapest one-way flight from Zurich to San Francisco in 3 weeks.'agent = Agent(task=task, llm=llm)diff --git a/examples/ui/command_line.py b/examples/ui/command_line.pyindex 7a7eb0113..dfe5c1c46 100644--- a/examples/ui/command_line.py+++ b/examples/ui/command_line.py@@ -31,15 +31,15 @@ from browser_use.controller.service import Controllerdef get_llm(provider: str):if provider == 'anthropic':- from langchain_anthropic import ChatAnthropic+ from browser_use.llm import ChatAnthropicapi_key = os.getenv('ANTHROPIC_API_KEY')if not api_key:raise ValueError('Error: ANTHROPIC_API_KEY is not set. Please provide a valid API key.')- return ChatAnthropic(model_name='claude-3-5-sonnet-20240620', timeout=25, stop=None, temperature=0.0)+ return ChatAnthropic(model='claude-3-5-sonnet-20240620', temperature=0.0)elif provider == 'openai':- from langchain_openai import ChatOpenAI+ from browser_use.llm import ChatOpenAIapi_key = os.getenv('OPENAI_API_KEY')if not api_key:diff --git a/examples/ui/gradio_demo.py b/examples/ui/gradio_demo.pyindex 635f3f4ee..3961f7678 100644--- a/examples/ui/gradio_demo.py+++ b/examples/ui/gradio_demo.py@@ -12,13 +12,13 @@ load_dotenv()# Third-party importsimport gradio as gr # type: ignore-from langchain_openai import ChatOpenAIfrom rich.console import Consolefrom rich.panel import Panelfrom rich.text import Text# Local module importsfrom browser_use import Agent+from browser_use.llm import ChatOpenAI@dataclassdiff --git a/examples/ui/streamlit_demo.py b/examples/ui/streamlit_demo.pyindex aa0316a20..2171f22bb 100644--- a/examples/ui/streamlit_demo.py+++ b/examples/ui/streamlit_demo.py@@ -28,16 +28,16 @@ if os.name == 'nt':# Function to get the LLM based on providerdef get_llm(provider: str):if provider == 'anthropic':- from langchain_anthropic import ChatAnthropic+ from browser_use.llm import ChatAnthropicapi_key = os.getenv('ANTHROPIC_API_KEY')if not api_key:st.error('Error: ANTHROPIC_API_KEY is not set. Please provide a valid API key.')st.stop()- return ChatAnthropic(model_name='claude-3-5-sonnet-20240620', timeout=25, stop=None, temperature=0.0)+ return ChatAnthropic(model='claude-3-5-sonnet-20240620', temperature=0.0)elif provider == 'openai':- from langchain_openai import ChatOpenAI+ from browser_use.llm import ChatOpenAIapi_key = os.getenv('OPENAI_API_KEY')if not api_key:diff --git a/examples/use-cases/captcha.py b/examples/use-cases/captcha.pyindex 98b0a6d10..9c012cd97 100644--- a/examples/use-cases/captcha.py+++ b/examples/use-cases/captcha.py@@ -18,9 +18,8 @@ from dotenv import load_dotenvload_dotenv()-from langchain_openai import ChatOpenAI-from browser_use import Agent+from browser_use.llm import ChatOpenAIif not os.getenv('OPENAI_API_KEY'):raise ValueError('OPENAI_API_KEY is not set. Please add it to your environment variables.')diff --git a/examples/use-cases/check_appointment.py b/examples/use-cases/check_appointment.pyindex 9e9dd792a..b4c695d24 100644--- a/examples/use-cases/check_appointment.py+++ b/examples/use-cases/check_appointment.py@@ -10,11 +10,11 @@ from dotenv import load_dotenvload_dotenv()-from langchain_openai import ChatOpenAI-from pydantic import BaseModel, SecretStr+from pydantic import BaseModelfrom browser_use.agent.service import Agentfrom browser_use.controller.service import Controller+from browser_use.llm import ChatOpenAIif not os.getenv('OPENAI_API_KEY'):raise ValueError('OPENAI_API_KEY is not set. Please add it to your environment variables.')@@ -42,7 +42,7 @@ async def main():'If there is no available date in both months, tell me there is no available date.')- model = ChatOpenAI(model='gpt-4o-mini', api_key=SecretStr(os.getenv('OPENAI_API_KEY', '')))+ model = ChatOpenAI(model='gpt-4o-mini')agent = Agent(task, model, controller=controller, use_vision=True)await agent.run()diff --git a/examples/use-cases/find_and_apply_to_jobs.py b/examples/use-cases/find_and_apply_to_jobs.pyindex c63102f7e..9eeb30c0d 100644--- a/examples/use-cases/find_and_apply_to_jobs.py+++ b/examples/use-cases/find_and_apply_to_jobs.py@@ -18,12 +18,12 @@ from dotenv import load_dotenvload_dotenv()-from langchain_openai import AzureChatOpenAI-from pydantic import BaseModel, SecretStr+from pydantic import BaseModelfrom PyPDF2 import PdfReader # type: ignorefrom browser_use import ActionResult, Agent, Controllerfrom browser_use.browser import BrowserProfile, BrowserSession+from browser_use.llm import ChatAzureOpenAIrequired_env_vars = ['AZURE_OPENAI_KEY', 'AZURE_OPENAI_ENDPOINT']for var in required_env_vars:@@ -136,11 +136,8 @@ async def main():# + 'go to https://nvidia.wd5.myworkdayjobs.com/en-US/NVIDIAExternalCareerSite/job/Taiwan%2C-Remote/Fulfillment-Analyst---New-College-Graduate-2025_JR1988949/apply/autofillWithResume?workerSubType=0c40f6bd1d8f10adf6dae42e46d44a17&workerSubType=ab40a98049581037a3ada55b087049b7 NVIDIA',# ground_task + '\n' + 'Meta',]- model = AzureChatOpenAI(+ model = ChatAzureOpenAI(model='gpt-4o',- api_version='2024-10-21',- azure_endpoint=os.getenv('AZURE_OPENAI_ENDPOINT', ''),- api_key=SecretStr(os.getenv('AZURE_OPENAI_KEY', '')),)agents = []diff --git a/examples/use-cases/find_influencer_profiles.py b/examples/use-cases/find_influencer_profiles.pyindex fa869da1b..862cb4589 100644--- a/examples/use-cases/find_influencer_profiles.py+++ b/examples/use-cases/find_influencer_profiles.py@@ -16,11 +16,11 @@ from dotenv import load_dotenvload_dotenv()import httpx-from langchain_openai import ChatOpenAIfrom pydantic import BaseModelfrom browser_use import Agent, Controllerfrom browser_use.agent.views import ActionResult+from browser_use.llm import ChatOpenAIclass Profile(BaseModel):diff --git a/examples/use-cases/google_sheets.py b/examples/use-cases/google_sheets.pyindex 5adf496c6..fec41880a 100644--- a/examples/use-cases/google_sheets.py+++ b/examples/use-cases/google_sheets.py@@ -5,10 +5,10 @@ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))import asynciofrom dotenv import load_dotenv-from langchain_openai import ChatOpenAIfrom browser_use import Agent, Controllerfrom browser_use.browser import BrowserProfile, BrowserSession+from browser_use.llm import ChatOpenAI# Load environment variablesload_dotenv()diff --git a/examples/use-cases/online_coding_agent.py b/examples/use-cases/online_coding_agent.pyindex bb5783ab5..59bd27eb1 100644--- a/examples/use-cases/online_coding_agent.py+++ b/examples/use-cases/online_coding_agent.py@@ -10,10 +10,9 @@ from dotenv import load_dotenvload_dotenv()-from langchain_openai import ChatOpenAI-from browser_use import Agentfrom browser_use.browser import BrowserSession+from browser_use.llm import ChatOpenAIif not os.getenv('OPENAI_API_KEY'):raise ValueError('OPENAI_API_KEY is not set. Please add it to your environment variables.')diff --git a/examples/use-cases/play_chess.py b/examples/use-cases/play_chess.pyindex 1e917e86c..912932d21 100755--- a/examples/use-cases/play_chess.py+++ b/examples/use-cases/play_chess.py@@ -18,12 +18,12 @@ import loggingimport chess # type: ignorefrom bs4 import BeautifulSoup-from langchain_openai import ChatOpenAIfrom pydantic import BaseModel, Fieldfrom browser_use import Agent, Controllerfrom browser_use.agent.views import ActionResultfrom browser_use.browser.context import BrowserContext+from browser_use.llm import ChatOpenAIif not os.getenv('OPENAI_API_KEY'):raise ValueError('OPENAI_API_KEY is not set. Please add it to your environment variables.')diff --git a/examples/use-cases/post-twitter.py b/examples/use-cases/post-twitter.pyindex c57a55556..0645be42f 100644--- a/examples/use-cases/post-twitter.py+++ b/examples/use-cases/post-twitter.py@@ -30,10 +30,9 @@ from dotenv import load_dotenvload_dotenv()-from langchain_openai import ChatOpenAI-from browser_use import Agent, Controllerfrom browser_use.browser import BrowserProfile, BrowserSession+from browser_use.llm import ChatOpenAIif not os.getenv('OPENAI_API_KEY'):raise ValueError('OPENAI_API_KEY is not set. Please add it to your environment variables.')@@ -69,9 +68,7 @@ config = TwitterConfig(def create_twitter_agent(config: TwitterConfig) -> Agent:- from pydantic import SecretStr-- llm = ChatOpenAI(model=config.model, api_key=SecretStr(config.openai_api_key))+ llm = ChatOpenAI(model=config.model, api_key=config.openai_api_key)browser_profile = BrowserProfile(headless=config.headless,diff --git a/examples/use-cases/scrolling_page.py b/examples/use-cases/scrolling_page.pyindex 3ecbac438..738ed475c 100644--- a/examples/use-cases/scrolling_page.py+++ b/examples/use-cases/scrolling_page.py@@ -10,10 +10,9 @@ from dotenv import load_dotenvload_dotenv()-from langchain_openai import ChatOpenAI-from browser_use import Agentfrom browser_use.browser import BrowserProfile, BrowserSession+from browser_use.llm import ChatOpenAIif not os.getenv('OPENAI_API_KEY'):raise ValueError('OPENAI_API_KEY is not set')diff --git a/examples/use-cases/shopping.py b/examples/use-cases/shopping.pyindex a0cf985b8..331ed82fc 100644--- a/examples/use-cases/shopping.py+++ b/examples/use-cases/shopping.py@@ -8,10 +8,9 @@ from dotenv import load_dotenvload_dotenv()-from langchain_openai import ChatOpenAI-from browser_use import Agentfrom browser_use.browser import BrowserSession+from browser_use.llm import ChatOpenAItask = """### Prompt for Shopping Agent – Migros Online Grocery Orderdiff --git a/examples/use-cases/twitter_post_using_cookies.py b/examples/use-cases/twitter_post_using_cookies.pyindex 74f29f4b3..3bf999975 100644--- a/examples/use-cases/twitter_post_using_cookies.py+++ b/examples/use-cases/twitter_post_using_cookies.py@@ -10,17 +10,16 @@ from dotenv import load_dotenvload_dotenv()-from langchain_google_genai import ChatGoogleGenerativeAI-from pydantic import SecretStrfrom browser_use import Agentfrom browser_use.browser import BrowserProfile, BrowserSession+from browser_use.llm import ChatGoogleapi_key = os.getenv('GOOGLE_API_KEY')if not api_key:raise ValueError('GOOGLE_API_KEY is not set')-llm = ChatGoogleGenerativeAI(model='gemini-2.0-flash-exp', api_key=SecretStr(api_key))+llm = ChatGoogle(model='gemini-2.0-flash-exp', api_key=api_key)browser_session = BrowserSession(diff --git a/examples/use-cases/web_voyager_agent.py b/examples/use-cases/web_voyager_agent.pyindex 68b1d2c1b..c8ab09fba 100644--- a/examples/use-cases/web_voyager_agent.py+++ b/examples/use-cases/web_voyager_agent.py@@ -11,11 +11,10 @@ from dotenv import load_dotenvload_dotenv()-from langchain_openai import AzureChatOpenAI, ChatOpenAI-from pydantic import SecretStrfrom browser_use.agent.service import Agentfrom browser_use.browser import BrowserProfile, BrowserSession+from browser_use.llm import ChatAzureOpenAI, ChatOpenAI# Set LLM based on defined environment variablesif os.getenv('OPENAI_API_KEY'):@@ -23,11 +22,8 @@ if os.getenv('OPENAI_API_KEY'):model='gpt-4o',)elif os.getenv('AZURE_OPENAI_KEY') and os.getenv('AZURE_OPENAI_ENDPOINT'):- llm = AzureChatOpenAI(+ llm = ChatAzureOpenAI(model='gpt-4o',- api_version='2024-10-21',- azure_endpoint=os.getenv('AZURE_OPENAI_ENDPOINT', ''),- api_key=SecretStr(os.getenv('AZURE_OPENAI_KEY', '')),)else:raise ValueError('No LLM found. Please set OPENAI_API_KEY or AZURE_OPENAI_KEY and AZURE_OPENAI_ENDPOINT.')diff --git a/examples/use-cases/wikipedia_banana_to_quantum.py b/examples/use-cases/wikipedia_banana_to_quantum.pyindex f6df63102..03fbc2eaa 100644--- a/examples/use-cases/wikipedia_banana_to_quantum.py+++ b/examples/use-cases/wikipedia_banana_to_quantum.py@@ -8,10 +8,9 @@ from dotenv import load_dotenvload_dotenv()-from langchain_openai import ChatOpenAI-from browser_use import Agentfrom browser_use.browser import BrowserProfile, BrowserSession+from browser_use.llm import ChatOpenAI# video https://preview.screen.studio/share/vuq91Ej8llm = ChatOpenAI(diff --git a/pyproject.toml b/pyproject.tomlindex 7873a4ce7..15d8c69cc 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -16,13 +16,6 @@ dependencies = ["bubus>=1.1.2","google-api-core>=2.25.0","httpx>=0.28.1",- "langchain-anthropic==0.3.15",- "langchain-core==0.3.64",- "langchain-deepseek>=0.1.3",- "langchain-google-genai==2.1.5",- "langchain-ollama==0.3.3",- "langchain-openai==0.3.21",- "langchain>=0.3.25","markdownify==1.1.0","mem0ai>=0.1.106","patchright>=1.52.5",@@ -38,6 +31,10 @@ dependencies = ["typing-extensions>=4.12.2","uuid7>=0.1.0","authlib>=1.6.0",+ "google-genai>=1.21.1",+ "openai>=1.81.0",+ "anthropic>=0.54.0",+ "groq>=0.28.0",]# google-api-core: only used for Google LLM APIs# pyperclip: only used for examples that use copy/paste@@ -64,7 +61,6 @@ cli = [examples = [# botocore: only needed for Bedrock Claude boto3 examples/models/bedrock_claude.py"botocore>=1.37.23",- # "langchain-aws>=0.2.24", # depends on version of numpy that doesnt have python 3.12 wheels yet, breaks CI"imgcat>=0.6.0","stagehand-py>=0.3.6","browserbase>=0.4.0",@@ -176,7 +172,6 @@ dev-dependencies = ["fastapi>=0.115.8","inngest>=0.4.19","uvicorn>=0.34.0",- "langchain-fireworks>=0.2.6","ipdb>=0.13.13","pre-commit>=4.2.0","codespell>=2.4.1",diff --git a/tests/ci/conftest.py b/tests/ci/conftest.pyindex 040853396..5641c7f8e 100644--- a/tests/ci/conftest.py+++ b/tests/ci/conftest.py@@ -6,14 +6,17 @@ Sets up environment variables to ensure tests never connect to production servicimport osimport tempfile-from unittest.mock import AsyncMock, MagicMock+from unittest.mock import AsyncMockimport pytestfrom dotenv import load_dotenv-from langchain_core.language_models import BaseChatModel-from langchain_core.messages import AIMessagefrom pytest_httpserver import HTTPServer+from browser_use.agent.views import AgentOutput+from browser_use.controller.service import Controller+from browser_use.llm import BaseChatModel+from browser_use.llm.views import ChatInvokeCompletion+# Load environment variables before any importsload_dotenv()@@ -62,7 +65,7 @@ def setup_test_environment():# not a fixture, mock_llm() provides this in a fixture below, this is a helper so that it can accept args-def create_mock_llm(actions=None):+def create_mock_llm(actions: list[str] | None = None) -> BaseChatModel:"""Create a mock LLM that returns specified actions or a default done action.Args:@@ -73,11 +76,18 @@ def create_mock_llm(actions=None):Returns:Mock LLM that will return the actions in order, or just a done action if no actions provided."""+ controller = Controller()+ ActionModel = controller.registry.create_action_model()+ AgentOutputWithActions = AgentOutput.type_with_custom_actions(ActionModel)+llm = AsyncMock(spec=BaseChatModel)- llm.model_name = 'mock-llm'+ llm.model = 'mock-llm'llm._verified_api_keys = True- llm._verified_tool_calling_method = 'raw'- # llm._verified_tool_calling_method = 'function_calling'++ # Add missing properties from BaseChatModel protocol+ llm.provider = 'mock'+ llm.name = 'mock-llm'+ llm.model_name = 'mock-llm' # Ensure this returns a string, not a mock# Default done actiondefault_done_action = """@@ -97,48 +107,41 @@ def create_mock_llm(actions=None):}"""- if actions is None:- # No actions provided, just return done action- async def async_invoke(*args, **kwargs):- return AIMessage(content=default_done_action)-- llm.invoke.return_value = AIMessage(content=default_done_action)- llm.ainvoke.side_effect = async_invoke- else:- # Actions provided, return them in sequence with structured output support- action_index = 0-- def get_next_action():- nonlocal action_index- if action_index < len(actions):- action = actions[action_index]- action_index += 1- return action- else:- return default_done_action-- async def mock_ainvoke(*args, **kwargs):- return AIMessage(content=get_next_action())+ # Unified logic for both cases+ action_index = 0- def mock_invoke(*args, **kwargs):- return AIMessage(content=get_next_action())+ def get_next_action() -> str:+ nonlocal action_index+ if actions is not None and action_index < len(actions):+ action = actions[action_index]+ action_index += 1+ return action+ else:+ return default_done_action- llm.invoke.side_effect = mock_invoke- llm.ainvoke.side_effect = mock_ainvoke+ async def mock_ainvoke(*args, **kwargs):+ # Check if output_format is provided (2nd argument or in kwargs)+ output_format = None+ if len(args) >= 2:+ output_format = args[1]+ elif 'output_format' in kwargs:+ output_format = kwargs['output_format']- # Mock the with_structured_output method to return parsed objects- structured_llm = MagicMock()+ action_json = get_next_action()- async def mock_structured_ainvoke(*args, **kwargs):- # The agent will create its own AgentOutput and ActionModel classes- # We return the raw response and let the agent parse it- return {- 'raw': AIMessage(content=get_next_action()),- 'parsed': None, # Let the agent parse it from the raw JSON- }+ if output_format is None:+ # Return string completion+ return ChatInvokeCompletion(completion=action_json, usage=None)+ else:+ # Parse with provided output_format (could be AgentOutputWithActions or another model)+ if output_format == AgentOutputWithActions:+ parsed = AgentOutputWithActions.model_validate_json(action_json)+ else:+ # For other output formats, try to parse the JSON with that model+ parsed = output_format.model_validate_json(action_json)+ return ChatInvokeCompletion(completion=parsed, usage=None)- structured_llm.ainvoke = AsyncMock(side_effect=mock_structured_ainvoke)- llm.with_structured_output = lambda *args, **kwargs: structured_llm+ llm.ainvoke.side_effect = mock_ainvokereturn llmdiff --git a/tests/ci/evaluate_tasks.py b/tests/ci/evaluate_tasks.pyindex 24f70ddbe..be033689a 100644--- a/tests/ci/evaluate_tasks.py+++ b/tests/ci/evaluate_tasks.py@@ -15,13 +15,14 @@ import warningsimport aiofilesimport yaml-from langchain_openai import ChatOpenAIfrom pydantic import BaseModelfrom browser_use.agent.service import Agentfrom browser_use.agent.views import AgentHistoryListfrom browser_use.browser.profile import BrowserProfilefrom browser_use.browser.session import BrowserSession+from browser_use.llm import ChatOpenAI+from browser_use.llm.messages import UserMessage# --- CONFIG ---MAX_PARALLEL = 10@@ -86,7 +87,10 @@ async def run_single_task(task_file):print(f"[DEBUG] Browser test: got title '{title}'", file=sys.stderr)except Exception as browser_error:print(f'[DEBUG] Browser test failed: {str(browser_error)}', file=sys.stderr)- print(f'[DEBUG] Browser error type: {type(browser_error).__name__}', file=sys.stderr)+ print(+ f'[DEBUG] Browser error type: {type(browser_error).__name__}',+ file=sys.stderr,+ )print('[DEBUG] Starting agent execution...', file=sys.stderr)agent = Agent(task=task, llm=agent_llm, browser_session=session)@@ -95,7 +99,10 @@ async def run_single_task(task_file):history: AgentHistoryList = await agent.run(max_steps=max_steps)print('[DEBUG] Agent.run() returned successfully', file=sys.stderr)except Exception as agent_error:- print(f'[DEBUG] Agent.run() failed with error: {str(agent_error)}', file=sys.stderr)+ print(+ f'[DEBUG] Agent.run() failed with error: {str(agent_error)}',+ file=sys.stderr,+ )print(f'[DEBUG] Error type: {type(agent_error).__name__}', file=sys.stderr)# Re-raise to be caught by outer try-catchraise agent_error@@ -105,8 +112,11 @@ async def run_single_task(task_file):# Test if LLM is working by making a simple calltry:- test_response = await agent_llm.ainvoke("Say 'test'")- print(f'[DEBUG] LLM test call successful: {test_response.content[:50]}', file=sys.stderr)+ response = await agent_llm.ainvoke([UserMessage(content="Say 'test'")])+ print(+ f'[DEBUG] LLM test call successful: {response.completion[:50]}',+ file=sys.stderr,+ )except Exception as llm_error:print(f'[DEBUG] LLM test call failed: {str(llm_error)}', file=sys.stderr)@@ -120,7 +130,10 @@ async def run_single_task(task_file):# Log to stderr so it shows up in GitHub Actions (won't interfere with JSON output to stdout)print(f'[DEBUG] Task {os.path.basename(task_file)}: {debug_info}', file=sys.stderr)if agent_output:- print(f'[DEBUG] Agent output preview: {agent_output[:200]}...', file=sys.stderr)+ print(+ f'[DEBUG] Agent output preview: {agent_output[:200]}...',+ file=sys.stderr,+ )else:print('[DEBUG] Agent produced no output!', file=sys.stderr)@@ -140,8 +153,8 @@ Criteria for success:Reply in JSON with keys: success (true/false), explanation (string).If the agent provided no output, explain what might have gone wrong."""- structured_llm = judge_llm.with_structured_output(JudgeResponse)- judge_response: JudgeResponse = await structured_llm.ainvoke(judge_prompt) # type: ignore[assignment]+ response = await judge_llm.ainvoke([UserMessage(content=judge_prompt)], output_format=JudgeResponse)+ judge_response = response.completionresult = {'file': os.path.basename(task_file),@@ -161,7 +174,11 @@ If the agent provided no output, explain what might have gone wrong.except Exception:pass- return {'file': os.path.basename(task_file), 'success': False, 'explanation': f'Task failed with error: {str(e)}'}+ return {+ 'file': os.path.basename(task_file),+ 'success': False,+ 'explanation': f'Task failed with error: {str(e)}',+ }async def run_task_subprocess(task_file, semaphore):@@ -295,7 +312,13 @@ async def main():# Output detailed results as JSON for GitHub Actionsdetailed_results = []for r in results:- detailed_results.append({'task': r['file'].replace('.yaml', ''), 'success': r['success'], 'reason': r['explanation']})+ detailed_results.append(+ {+ 'task': r['file'].replace('.yaml', ''),+ 'success': r['success'],+ 'reason': r['explanation'],+ }+ )print('DETAILED_RESULTS=' + json.dumps(detailed_results))diff --git a/tests/ci/test_agent_multiprocessing.py b/tests/ci/test_agent_multiprocessing.pyindex 71b08ca40..7954a0988 100644--- a/tests/ci/test_agent_multiprocessing.py+++ b/tests/ci/test_agent_multiprocessing.py@@ -15,10 +15,6 @@ import asyncioimport loggingimport multiprocessingfrom concurrent.futures import ThreadPoolExecutor-from unittest.mock import AsyncMock--from langchain_core.language_models.chat_models import BaseChatModel-from langchain_core.messages import AIMessagefrom browser_use import Agent, setup_loggingfrom browser_use.browser import BrowserProfile, BrowserSession@@ -42,40 +38,11 @@ def run_agent_in_subprocess_module(task_description):async def run_agent():# Create mock LLM inline to avoid pickling issues- mock_llm = AsyncMock(spec=BaseChatModel)- mock_llm._verified_api_keys = True- mock_llm._verified_tool_calling_method = 'raw'- mock_llm.model_name = 'mock-llm'-- response_content = """- {- "thinking": "null",- "evaluation_previous_goal": "Starting the task",- "memory": "Task completed",- "next_goal": "Complete the task",- "action": [- {- "done": {- "text": "Task completed successfully",- "success": true- }- }- ]- }- """-- mock_llm.invoke.return_value = AIMessage(content=response_content)-- # Make ainvoke return a coroutine- async def async_invoke(*args, **kwargs):- return AIMessage(content=response_content)-- mock_llm.ainvoke.side_effect = async_invoke+ mock_llm = create_mock_llm()agent = Agent(task=task_description,llm=mock_llm,- tool_calling_method='raw',enable_memory=False,browser_profile=BrowserProfile(headless=True, user_data_dir=None),)@@ -124,7 +91,6 @@ class TestParallelism:agent = Agent(task='Test task',llm=mock_llm,- tool_calling_method='raw',enable_memory=False,browser_profile=BrowserProfile(headless=True, user_data_dir=None),)@@ -162,7 +128,6 @@ class TestParallelism:task='First parallel task',llm=mock_llm,browser_session=browser_session,- tool_calling_method='raw',enable_memory=False,)@@ -170,7 +135,6 @@ class TestParallelism:task='Second parallel task',llm=mock_llm,browser_session=browser_session,- tool_calling_method='raw',enable_memory=False,)@@ -214,7 +178,6 @@ class TestParallelism:task='First sequential task',llm=mock_llm,browser_session=browser_session,- tool_calling_method='raw',enable_memory=False,)result1 = await agent1.run()@@ -224,7 +187,6 @@ class TestParallelism:task='Second sequential task',llm=mock_llm,browser_session=browser_session,- tool_calling_method='raw',enable_memory=False,)result2 = await agent2.run()@@ -253,7 +215,6 @@ class TestParallelism:agent1 = Agent(task='First loop task',llm=mock_llm,- tool_calling_method='raw',enable_memory=False,browser_profile=BrowserProfile(headless=True, user_data_dir=None),)@@ -262,7 +223,6 @@ class TestParallelism:agent2 = Agent(task='Second loop task',llm=mock_llm,- tool_calling_method='raw',enable_memory=False,browser_profile=BrowserProfile(headless=True, user_data_dir=None),)@@ -296,7 +256,6 @@ class TestParallelism:agent = Agent(task=task_description,llm=mock_llm,- tool_calling_method='raw',enable_memory=False,browser_profile=BrowserProfile(headless=True, user_data_dir=None),)@@ -419,7 +378,6 @@ class TestParallelism:task='Task in tab 1',llm=mock_llm1,browser_session=shared_session,- tool_calling_method='raw',enable_memory=False,)@@ -427,7 +385,6 @@ class TestParallelism:task='Task in tab 2',llm=mock_llm2,browser_session=shared_session,- tool_calling_method='raw',enable_memory=False,)@@ -481,7 +438,6 @@ class TestParallelism:task='First task',llm=mock_llm,browser_session=session,- tool_calling_method='raw',enable_memory=False,)result1 = await agent1.run()@@ -495,7 +451,6 @@ class TestParallelism:task='Second task',llm=mock_llm,browser_session=session,- tool_calling_method='raw',enable_memory=False,)result2 = await agent2.run()@@ -541,7 +496,6 @@ class TestParallelism:task='Test with existing playwright objects',llm=mock_llm,browser_session=browser_session,- tool_calling_method='raw',enable_memory=False,)diff --git a/tests/ci/test_agent_sensitive_data.py b/tests/ci/test_agent_sensitive_data.pyindex 4edada7aa..d1a83520b 100644--- a/tests/ci/test_agent_sensitive_data.py+++ b/tests/ci/test_agent_sensitive_data.py@@ -1,11 +1,12 @@import pytest-from langchain_core.messages import HumanMessage, SystemMessagefrom pydantic import BaseModel, Fieldfrom browser_use.agent.message_manager.service import MessageManager, MessageManagerSettingsfrom browser_use.agent.views import MessageManagerStatefrom browser_use.controller.registry.service import Registryfrom browser_use.filesystem.file_system import FileSystem+from browser_use.llm import SystemMessage, UserMessage+from browser_use.llm.messages import ContentPartTextParamfrom browser_use.utils import match_url_with_domain_pattern@@ -248,7 +249,7 @@ def test_url_components():def test_filter_sensitive_data(message_manager):"""Test that _filter_sensitive_data handles all sensitive data scenarios correctly"""# Set up a message with sensitive information- message = HumanMessage(content='My username is admin and password is secret123')+ message = UserMessage(content='My username is admin and password is secret123')# Case 1: No sensitive data providedmessage_manager.settings.sensitive_data = None@@ -262,10 +263,10 @@ def test_filter_sensitive_data(message_manager):assert '<secret>password</secret>' in result.content# Case 3: Make sure it works with nested content- nested_message = HumanMessage(content=[{'type': 'text', 'text': 'My username is admin and password is secret123'}])+ nested_message = UserMessage(content=[ContentPartTextParam(text='My username is admin and password is secret123')])result = message_manager._filter_sensitive_data(nested_message)- assert '<secret>username</secret>' in result.content[0]['text']- assert '<secret>password</secret>' in result.content[0]['text']+ assert '<secret>username</secret>' in result.content[0].text+ assert '<secret>password</secret>' in result.content[0].text# Case 4: Test with empty valuesmessage_manager.settings.sensitive_data = {'username': 'admin', 'password': ''}@@ -279,7 +280,7 @@ def test_filter_sensitive_data(message_manager):'google.com': {'email': '[email protected]', 'password': 'google_pass'},}# Update the message to include the values we're going to test- message = HumanMessage(content='My username is admin, email is [email protected] and password is secret123 or google_pass')+ message = UserMessage(content='My username is admin, email is [email protected] and password is secret123 or google_pass')result = message_manager._filter_sensitive_data(message)# All sensitive values should be replaced regardless of domainassert '<secret>username</secret>' in result.contentdiff --git a/tests/ci/test_browser_session_start.py b/tests/ci/test_browser_session_start.pyindex a91a77fcd..ab3d3f52a 100644--- a/tests/ci/test_browser_session_start.py+++ b/tests/ci/test_browser_session_start.py@@ -590,7 +590,6 @@ class TestBrowserSessionReusePatterns:task='The first task...',llm=mock_llm,browser_profile=reused_profile,- tool_calling_method='raw', # Use raw mode for testsenable_memory=False, # Disable memory for tests)await agent1.run()@@ -604,7 +603,6 @@ class TestBrowserSessionReusePatterns:task='The second task...',llm=mock_llm,browser_profile=reused_profile,- tool_calling_method='raw', # Use raw mode for testsenable_memory=False, # Disable memory for tests)await agent2.run()@@ -636,7 +634,6 @@ class TestBrowserSessionReusePatterns:task='The first task...',llm=mock_llm,browser_session=reused_session,- tool_calling_method='raw', # Use raw mode for testsenable_memory=False, # Disable memory for tests)await agent1.run()@@ -650,7 +647,6 @@ class TestBrowserSessionReusePatterns:task='The second task...',llm=mock_llm,browser_session=reused_session,- tool_calling_method='raw', # Use raw mode for testsenable_memory=False, # Disable memory for tests)await agent2.run()@@ -744,21 +740,18 @@ class TestBrowserSessionReusePatterns:task='First parallel task...',llm=mock_llm1,browser_session=shared_browser,- tool_calling_method='raw', # Use raw mode for testsenable_memory=False, # Disable memory for tests)agent2 = Agent(task='Second parallel task...',llm=mock_llm2,browser_session=shared_browser,- tool_calling_method='raw', # Use raw mode for testsenable_memory=False, # Disable memory for tests)agent3 = Agent(task='Third parallel task...',llm=mock_llm3,browser_session=shared_browser,- tool_calling_method='raw', # Use raw mode for testsenable_memory=False, # Disable memory for tests)@@ -813,14 +806,12 @@ class TestBrowserSessionReusePatterns:task='Fill out the form in section A...',llm=mock_llm,browser_session=shared_browser,- tool_calling_method='raw', # Use raw mode for testsenable_memory=False, # Disable memory for tests)agent2 = Agent(task='Fill out the form in section B...',llm=mock_llm,browser_session=shared_browser,- tool_calling_method='raw', # Use raw mode for testsenable_memory=False, # Disable memory for tests)@@ -868,15 +859,11 @@ class TestBrowserSessionReusePatterns:# Create separate browser sessions from the same profilewindow1 = BrowserSession(browser_profile=shared_profile)await window1.start()- agent1 = Agent(- task='First agent task...', llm=mock_llm, browser_session=window1, tool_calling_method='raw', enable_memory=False- )+ agent1 = Agent(task='First agent task...', llm=mock_llm, browser_session=window1, enable_memory=False)window2 = BrowserSession(browser_profile=shared_profile)await window2.start()- agent2 = Agent(- task='Second agent task...', llm=mock_llm, browser_session=window2, tool_calling_method='raw', enable_memory=False- )+ agent2 = Agent(task='Second agent task...', llm=mock_llm, browser_session=window2, enable_memory=False)# Run agents in parallel_results = await asyncio.gather(agent1.run(), agent2.run())diff --git a/tests/ci/test_registry.py b/tests/ci/test_registry.pyindex 04fb24729..5fb088852 100644--- a/tests/ci/test_registry.py+++ b/tests/ci/test_registry.py@@ -30,6 +30,7 @@ from browser_use.controller.views import (NoParamsAction,SearchGoogleAction,)+from browser_use.llm.messages import UserMessagefrom tests.ci.conftest import create_mock_llm# Configure logging@@ -208,7 +209,7 @@ class TestActionRegistryParameterPatterns:async def test_mixed_special_parameters(self, registry, browser_session, base_url, mock_llm):"""Test action with multiple special injected parameters"""- from langchain_core.language_models.chat_models import BaseChatModel+ from browser_use.llm.base import BaseChatModel@registry.action('Action with multiple special params')async def multi_special_action(@@ -217,11 +218,11 @@ class TestActionRegistryParameterPatterns:page_extraction_llm: BaseChatModel,available_file_paths: list,):- llm_response = await page_extraction_llm.ainvoke('test')+ llm_response = await page_extraction_llm.ainvoke([UserMessage(content='test')])files = available_file_paths or []return ActionResult(- extracted_content=f'Text: {text}, URL: {page.url}, LLM: {llm_response.content}, Files: {len(files)}'+ extracted_content=f'Text: {text}, URL: {page.url}, LLM: {llm_response.completion}, Files: {len(files)}')# Navigate to test page first@@ -491,13 +492,13 @@ class TestRegistryEdgeCases:async def test_missing_required_llm(self, registry, browser_session):"""Test that actions requiring page_extraction_llm fail appropriately when not provided"""- from langchain_core.language_models.chat_models import BaseChatModel+ from browser_use.llm.base import BaseChatModel@registry.action('Requires LLM')async def requires_llm(text: str, browser_session: BrowserSession, page_extraction_llm: BaseChatModel):page = await browser_session.get_current_page()- llm_response = await page_extraction_llm.ainvoke('test')- return ActionResult(extracted_content=f'Text: {text}, LLM: {llm_response.content}')+ llm_response = await page_extraction_llm.ainvoke([UserMessage(content='test')])+ return ActionResult(extracted_content=f'Text: {text}, LLM: {llm_response.completion}')# Should raise RuntimeError when page_extraction_llm is required but not providedwith pytest.raises(RuntimeError, match='requires page_extraction_llm but none provided'):@@ -675,7 +676,7 @@ class TestType1Pattern:goal: strinclude_links: bool = False- from langchain_core.language_models.chat_models import BaseChatModel+ from browser_use.llm.base import BaseChatModel@registry.action('Extract content', param_model=ExtractAction)async def extract_content(@@ -964,7 +965,7 @@ class TestParameterOrdering:def test_mixed_param_ordering(self):"""Should handle any ordering of action params and special params"""registry = Registry()- from langchain_core.language_models.chat_models import BaseChatModel+ from browser_use.llm.base import BaseChatModel# Special params mixed throughout@registry.action('Mixed params')diff --git a/tests/old/extraction_test.py b/tests/old/extraction_test.pyindex 31c125ae6..59f8fc332 100644--- a/tests/old/extraction_test.py+++ b/tests/old/extraction_test.py@@ -2,34 +2,12 @@ import asyncioimport osimport anyio-from langchain_openai import ChatOpenAIfrom browser_use.agent.prompts import AgentMessagePromptfrom browser_use.browser import BrowserProfile, BrowserSessionfrom browser_use.dom.service import DomServicefrom browser_use.filesystem.file_system import FileSystem--def count_string_tokens(string: str, model: str) -> tuple[int, float]:- """Count the number of tokens in a string using a specified model."""-- def get_price_per_token(model: str) -> float:- """Get the price per token for a specified model.-- @todo: move to utils, use a package or sth- """- prices = {- 'gpt-4o': 2.5 / 1e6,- 'gpt-4o-mini': 0.15 / 1e6,- }- return prices[model]-- llm = ChatOpenAI(model=model)- token_count = llm.get_num_tokens(string)- price = token_count * get_price_per_token(model)- return token_count, price--TIMEOUT = 60DEFAULT_INCLUDE_ATTRIBUTES = [@@ -102,7 +80,7 @@ async def test_focus_vs_all_elements():# print(all_elements_state.element_tree.clickable_elements_to_string())prompt = AgentMessagePrompt(browser_state_summary=all_elements_state,- file_system=FileSystem(working_dir='./tmp'),+ file_system=FileSystem(dir_path='./tmp'),include_attributes=DEFAULT_INCLUDE_ATTRIBUTES,step_info=None,)@@ -116,11 +94,6 @@ async def test_focus_vs_all_elements():else:await f.write(str(user_message))- if isinstance(user_message, str):- token_count, price = count_string_tokens(user_message, model='gpt-4o')- else:- token_count, price = count_string_tokens(str(user_message), model='gpt-4o')- print(f'Prompt token count: {token_count}, price: {round(price, 4)} USD')print('User message written to ./tmp/user_message.txt')# also save all_elements_state.element_tree.clickable_elements_to_string() to a filediff --git a/tests/old/test_agent_actions.py b/tests/old/test_agent_actions.pyindex 721be1e41..0a38b6989 100644--- a/tests/old/test_agent_actions.py+++ b/tests/old/test_agent_actions.py@@ -1,12 +1,10 @@-import os-import pytest-from langchain_openai import AzureChatOpenAI-from pydantic import BaseModel, SecretStr+from pydantic import BaseModelfrom browser_use.agent.service import Agentfrom browser_use.agent.views import AgentHistoryListfrom browser_use.browser import BrowserSession+from browser_use.llm import ChatAzureOpenAI@pytest.fixture@@ -14,11 +12,8 @@ def llm():"""Initialize language model for testing"""# return ChatAnthropic(model_name='claude-3-5-sonnet-20240620', timeout=25, stop=None)- return AzureChatOpenAI(+ return ChatAzureOpenAI(model='gpt-4o',- api_version='2024-10-21',- azure_endpoint=os.getenv('AZURE_OPENAI_ENDPOINT', ''),- api_key=SecretStr(os.getenv('AZURE_OPENAI_KEY', '')),)# return ChatOpenAI(model='gpt-4o-mini')diff --git a/tests/old/test_core_functionality.py b/tests/old/test_core_functionality.pyindex 47ede5266..4368a1910 100644--- a/tests/old/test_core_functionality.py+++ b/tests/old/test_core_functionality.py@@ -1,8 +1,8 @@import pytest-from langchain_openai import ChatOpenAIfrom pytest_httpserver import HTTPServerfrom browser_use import setup_logging+from browser_use.llm import ChatOpenAIsetup_logging()diff --git a/tests/old/test_dropdown_error.py b/tests/old/test_dropdown_error.pyindex ff6226753..dedb723dd 100644--- a/tests/old/test_dropdown_error.py+++ b/tests/old/test_dropdown_error.py@@ -11,9 +11,8 @@ from browser_use.browser import BrowserProfile, BrowserSessionsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))-from langchain_openai import ChatOpenAI-from browser_use import Agent, AgentHistoryList+from browser_use.llm import ChatOpenAIllm = ChatOpenAI(model='gpt-4o')browser_session = BrowserSession(browser_profile=BrowserProfile(headless=True))diff --git a/tests/old/test_gif_path.py b/tests/old/test_gif_path.pyindex 84d4b441a..31bb0dd24 100644--- a/tests/old/test_gif_path.py+++ b/tests/old/test_gif_path.py@@ -11,9 +11,8 @@ from browser_use.browser import BrowserProfile, BrowserSessionsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))-from langchain_openai import ChatOpenAI-from browser_use import Agent, AgentHistoryList+from browser_use.llm import ChatOpenAIllm = ChatOpenAI(model='gpt-4o')diff --git a/tests/old/test_mind2web.py b/tests/old/test_mind2web.pyindex 8b62cf1db..9156818d4 100644--- a/tests/old/test_mind2web.py+++ b/tests/old/test_mind2web.py@@ -7,11 +7,10 @@ import osfrom typing import Anyimport pytest-from langchain_openai import AzureChatOpenAI-from pydantic import SecretStrfrom browser_use.agent.service import Agentfrom browser_use.browser import BrowserProfile, BrowserSession+from browser_use.llm.azure.chat import ChatAzureOpenAIfrom browser_use.utils import logger# Constants@@ -50,11 +49,8 @@ def llm():"""Initialize language model for testing"""# return ChatAnthropic(model_name='claude-3-5-sonnet-20240620', timeout=25, stop=None)- return AzureChatOpenAI(+ return ChatAzureOpenAI(model='gpt-4o',- api_version='2024-10-21',- azure_endpoint=os.getenv('AZURE_OPENAI_ENDPOINT', ''),- api_key=SecretStr(os.getenv('AZURE_OPENAI_KEY', '')),)diff --git a/tests/old/test_models.py b/tests/old/test_models.pydeleted file mode 100644index dfe355ee4..000000000--- a/tests/old/test_models.py+++ /dev/null@@ -1,154 +0,0 @@-import os--import httpx-import pytest-from langchain_anthropic import ChatAnthropic-from langchain_google_genai import ChatGoogleGenerativeAI-from langchain_ollama import ChatOllama-from langchain_openai import AzureChatOpenAI, ChatOpenAI-from pydantic import SecretStr--from browser_use.agent.service import Agent-from browser_use.agent.views import AgentHistoryList-from browser_use.browser import BrowserProfile, BrowserSession--# Set env vars for testing-os.environ.setdefault('SKIP_LLM_API_KEY_VERIFICATION', 'true')-os.environ.setdefault('AZURE_OPENAI_ENDPOINT', 'https://test.openai.azure.com')-os.environ.setdefault('AZURE_OPENAI_KEY', 'test-key')-os.environ.setdefault('ANTHROPIC_API_KEY', 'test-key')-os.environ.setdefault('GOOGLE_API_KEY', 'test-key')-os.environ.setdefault('DEEPSEEK_API_KEY', 'test-key')-os.environ.setdefault('OPENAI_API_KEY', 'test-key')---async def browser_session():- browser_session = BrowserSession(- browser_profile=BrowserProfile(- headless=True,- )- )- await browser_session.start()- yield browser_session- await browser_session.stop()---api_key_gemini = SecretStr(os.getenv('GOOGLE_API_KEY') or '')-api_key_deepseek = SecretStr(os.getenv('DEEPSEEK_API_KEY') or '')-api_key_anthropic = SecretStr(os.getenv('ANTHROPIC_API_KEY') or '')---# pytest -s -v tests/test_models.py- params=[- ChatOpenAI(model='gpt-4o'),- ChatOpenAI(model='gpt-4o-mini'),- AzureChatOpenAI(- model='gpt-4o',- api_version='2024-10-21',- azure_endpoint=os.getenv('AZURE_OPENAI_ENDPOINT', ''),- api_key=SecretStr(os.getenv('AZURE_OPENAI_KEY', '')),- ),- # ChatOpenAI(- # base_url='https://api.deepseek.com/v1',- # model='deepseek-reasoner',- # api_key=api_key_deepseek,- # ),- # run: ollama start- ChatOllama(- model='qwen2.5:latest',- num_ctx=128000,- ),- AzureChatOpenAI(- model='gpt-4o-mini',- api_version='2024-10-21',- azure_endpoint=os.getenv('AZURE_OPENAI_ENDPOINT', ''),- api_key=SecretStr(os.getenv('AZURE_OPENAI_KEY', '')),- ),- ChatAnthropic(- model_name='claude-3-5-sonnet-20240620',- timeout=100,- temperature=0.0,- stop=None,- api_key=api_key_anthropic,- ),- ChatGoogleGenerativeAI(model='gemini-2.0-flash-exp', api_key=api_key_gemini),- ChatGoogleGenerativeAI(model='gemini-1.5-pro', api_key=api_key_gemini),- ChatGoogleGenerativeAI(model='gemini-1.5-flash-latest', api_key=api_key_gemini),- ChatOpenAI(- base_url='https://api.deepseek.com/v1',- model='deepseek-chat',- api_key=api_key_deepseek,- ),- ],- ids=[- 'gpt-4o',- 'gpt-4o-mini',- 'azure-gpt-4o',- #'deepseek-reasoner',- 'qwen2.5:latest',- 'azure-gpt-4o-mini',- 'claude-3-5-sonnet',- 'gemini-2.0-flash-exp',- 'gemini-1.5-pro',- 'gemini-1.5-flash-latest',- 'deepseek-chat',- ],-)-async def llm(request):- return request.param---async def test_model_search(llm, browser_session):- """Test 'Search Google' action"""- model_name = llm.model if hasattr(llm, 'model') else llm.model_name- print(f'\nTesting model: {model_name}')-- use_vision = True- models_without_vision = ['deepseek-chat', 'deepseek-reasoner']- if hasattr(llm, 'model') and llm.model in models_without_vision:- use_vision = False- elif hasattr(llm, 'model_name') and llm.model_name in models_without_vision:- use_vision = False-- # require ollama run- local_models = ['qwen2.5:latest']- if model_name in local_models:- # check if ollama is running- # ping ollama http://127.0.0.1- try:- async with httpx.AsyncClient() as client:- response = await client.get('http://127.0.0.1:11434/')- if response.status_code != 200:- raise Exception('Ollama is not running - start with `ollama start`')- except Exception:- raise Exception('Ollama is not running - start with `ollama start`')-- agent = Agent(- task="Search Google for 'elon musk' then click on the first result and scroll down.",- llm=llm,- browser_session=browser_session,- max_failures=2,- use_vision=use_vision,- )- history: AgentHistoryList = await agent.run(max_steps=2)- done = history.is_done()- successful = history.is_successful()- action_names = history.action_names()- print(f'Actions performed: {action_names}')- errors = [e for e in history.errors() if e is not None]- errors = '\n'.join(errors)- passed = False- if 'search_google' in action_names:- passed = True- elif 'go_to_url' in action_names:- passed = True- elif 'open_tab' in action_names:- passed = True-- else:- passed = False- print(f'Model {model_name}: {"✅ PASSED - " if passed else "❌ FAILED - "} Done: {done} Successful: {successful}')-- assert passed, f'Model {model_name} not working\nActions performed: {action_names}\nErrors: {errors}'diff --git a/tests/old/test_qwen.py b/tests/old/test_qwen.pydeleted file mode 100644index f847a4453..000000000--- a/tests/old/test_qwen.py+++ /dev/null@@ -1,51 +0,0 @@-import pytest-from langchain_ollama import ChatOllama--from browser_use.agent.service import Agent-from browser_use.agent.views import AgentHistoryList-from browser_use.browser import BrowserProfile, BrowserSession---def llm():- """Initialize language model for testing"""-- # return ChatAnthropic(model_name='claude-3-5-sonnet-20240620', timeout=25, stop=None)- # NOTE: Make sure to run ollama server with `ollama start'- return ChatOllama(- model='qwen2.5:latest',- num_ctx=128000,- )---async def browser_session():- browser_session = BrowserSession(- browser_profile=BrowserProfile(- headless=True,- )- )- await browser_session.start()- yield browser_session- await browser_session.stop()---# pytest tests/test_qwen.py -v -k "test_qwen_url" --capture=no-async def test_qwen_url(llm, browser_session):- """Test complex ecommerce interaction sequence"""- agent = Agent(- task='go_to_url amazon.com',- llm=llm,- browser_session=browser_session,- )-- history: AgentHistoryList = await agent.run(max_steps=3)-- # Verify sequence of actions- action_sequence = []- for action in history.model_actions():- action_name = list(action.keys())[0]- if action_name in ['go_to_url', 'open_tab']:- action_sequence.append('navigate')-- assert 'navigate' in action_sequence # Navigated to Amazondiff --git a/tests/old/test_react_dropdown.py b/tests/old/test_react_dropdown.pyindex d0648476e..f15287f6b 100644--- a/tests/old/test_react_dropdown.py+++ b/tests/old/test_react_dropdown.py@@ -12,9 +12,8 @@ from browser_use.browser import BrowserProfile, BrowserSessionsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))import asyncio-from langchain_openai import ChatOpenAI-from browser_use import Agent, AgentHistoryList+from browser_use.llm import ChatOpenAIllm = ChatOpenAI(model='gpt-4o')diff --git a/tests/old/test_self_registered_actions.py b/tests/old/test_self_registered_actions.pyindex 22ace11b2..87c467064 100644--- a/tests/old/test_self_registered_actions.py+++ b/tests/old/test_self_registered_actions.py@@ -1,13 +1,11 @@-import os-import pytest-from langchain_openai import AzureChatOpenAI-from pydantic import BaseModel, SecretStr+from pydantic import BaseModelfrom browser_use.agent.service import Agentfrom browser_use.agent.views import AgentHistoryListfrom browser_use.browser import BrowserProfile, BrowserSessionfrom browser_use.controller.service import Controller+from browser_use.llm import ChatAzureOpenAI@pytest.fixture@@ -79,11 +77,8 @@ def llm():"""Initialize language model for testing"""# return ChatAnthropic(model_name='claude-3-5-sonnet-20240620', timeout=25, stop=None)- return AzureChatOpenAI(+ return ChatAzureOpenAI(model='gpt-4o',- api_version='2024-10-21',- azure_endpoint=os.getenv('AZURE_OPENAI_ENDPOINT', ''),- api_key=SecretStr(os.getenv('AZURE_OPENAI_KEY', '')),)diff --git a/tests/old/test_vision.py b/tests/old/test_vision.pyindex f8affde31..600e0af17 100644--- a/tests/old/test_vision.py+++ b/tests/old/test_vision.py@@ -13,9 +13,8 @@ import pytestsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))-from langchain_openai import ChatOpenAI-from browser_use import Agent, AgentHistoryList, BrowserSession, Controller+from browser_use.llm import ChatOpenAIllm = ChatOpenAI(model='gpt-4o')controller = Controller()diff --git a/tests/old/test_wait_for_element.py b/tests/old/test_wait_for_element.pyindex b56feec9c..940e946e1 100644--- a/tests/old/test_wait_for_element.py+++ b/tests/old/test_wait_for_element.py@@ -2,13 +2,14 @@ import asyncioimport osimport sys+from browser_use.llm.openai.chat import ChatOpenAI+project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))if project_root not in sys.path:sys.path.insert(0, project_root)import pytestfrom dotenv import load_dotenv-from langchain_openai import ChatOpenAI# Third-party importsfrom browser_use import Agent, Controller