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
Fix
mertunsallb3e83d6d05f1
diff --git a/THINKING_FIELD_OPTIONAL_PR_SUMMARY.md b/THINKING_FIELD_OPTIONAL_PR_SUMMARY.mddeleted file mode 100644index 7ceeef851..000000000--- a/THINKING_FIELD_OPTIONAL_PR_SUMMARY.md+++ /dev/null@@ -1,122 +0,0 @@-# PR: Make Thinking Field Optional in Browser-Use Agent--This PR implements the feature to optionally deactivate the thinking field in the browser-use agent, providing a more concise output format when detailed reasoning is not needed.--## Overview--The browser-use agent previously required a `thinking` field in its structured output, which contained detailed reasoning about the agent's decision-making process. This PR adds the ability to disable this field, making the output more streamlined for use cases where detailed reasoning is not required.--## Changes Made--### 1. Added `use_thinking` Setting--**File:** `browser_use/agent/views.py`-- Added `use_thinking: bool = True` to `AgentSettings` class-- Made `thinking` field optional (`str | None = None`) in both `AgentBrain` and `AgentOutput` models-- Added `type_with_custom_actions_no_thinking()` static method for creating AgentOutput models without thinking field--### 2. Created Separate System Prompt for No-Thinking Mode--**File:** `browser_use/agent/system_prompt_no_thinking.md`-- New system prompt template that excludes all thinking-related instructions-- Focuses on evaluation, memory, next_goal, and actions only-- Provides clear and concise reasoning rules without requiring extensive thinking blocks--### 3. Updated System Prompt Loading Logic--**File:** `browser_use/agent/prompts.py`-- Modified `SystemPrompt` class to accept `use_thinking` parameter-- Added `_load_prompt_template()` method that automatically selects the appropriate template:- - `system_prompt.md` when `use_thinking=True` (default)- - `system_prompt_no_thinking.md` when `use_thinking=False`--### 4. Enhanced Agent Service--**File:** `browser_use/agent/service.py`-- Added `use_thinking` parameter to Agent constructor-- Updated `_setup_action_models()` to create appropriate output models based on thinking setting-- Updated `_update_action_models_for_page()` to handle both thinking and no-thinking models-- Modified `log_response()` function to handle cases where thinking might be None-- **RESTORED CRITICAL CODE**: Fixed accidentally removed new elements detection code in `multi_act()` method that prevents action sequence interruption when new elements appear--### 5. Updated Message Manager--**File:** `browser_use/agent/message_manager/service.py`-- Added `use_thinking` parameter to MessageManager constructor-- Modified `_init_messages()` to provide different examples based on thinking setting:- - Full thinking examples when `use_thinking=True`- - Concise examples without thinking field when `use_thinking=False`-- Updated `_update_agent_history_description()` to handle None thinking values-- Fixed redundant newlines in file content examples (e.g., `"# Github Repositories:\n"` instead of multiline strings)-- **FIXED TAGS**: Updated `add_new_task()` method to use `<system>` tags instead of `<s>` tags--### 6. Fixed System Message Tags--**Both system prompt files:**-- Changed `<s>` tags to `<system>` tags for consistency-- Changed `<o>` tags to `<output>` tags for better clarity-- Updated all references to use the new tag format--### 7. Updated Agent History Serialization--**File:** `browser_use/agent/views.py`-- Enhanced `AgentHistory.model_dump()` to conditionally include thinking field only when present-- Ensures clean serialization when thinking is disabled--## Usage--### Basic Usage with Thinking (Default)-```python-from browser_use import Agent-from browser_use.llm import ChatOpenAI--agent = Agent(- task="Find information about browser automation",- llm=ChatOpenAI(model="gpt-4o"),- use_thinking=True # Default behavior - includes thinking field-)-```--### Streamlined Usage without Thinking-```python-from browser_use import Agent-from browser_use.llm import ChatOpenAI--agent = Agent(- task="Find information about browser automation",- llm=ChatOpenAI(model="gpt-4o"),- use_thinking=False # Disables thinking field for cleaner output-)-```--## Benefits--1. **Reduced Token Usage**: Eliminates thinking field when not needed, saving tokens and costs-2. **Faster Processing**: Less content to generate and process-3. **Cleaner Output**: More focused responses for production use cases-4. **Backward Compatibility**: Default behavior unchanged (`use_thinking=True`)-5. **Debugging Flexibility**: Can still enable thinking for development and debugging--## Testing--The implementation has been tested to ensure:-- ✅ Default behavior remains unchanged (`use_thinking=True`)-- ✅ New no-thinking mode works correctly (`use_thinking=False`)-- ✅ System prompts load correctly for both modes-- ✅ Examples are provided appropriately for each mode-- ✅ Agent output models are created correctly-- ✅ History serialization handles optional thinking field-- ✅ Message manager creates appropriate examples-- ✅ All tags are consistent (`<system>` and `<output>`)-- ✅ Critical multi-action functionality preserved--## Files Modified--1. `browser_use/agent/views.py` - Core models and settings-2. `browser_use/agent/system_prompt_no_thinking.md` - New system prompt (created)-3. `browser_use/agent/system_prompt.md` - Updated tags-4. `browser_use/agent/prompts.py` - System prompt loading logic-5. `browser_use/agent/service.py` - Agent initialization and model setup-6. `browser_use/agent/message_manager/service.py` - Message handling and examples--This PR provides a clean, optional way to disable the thinking field while maintaining full backward compatibility and preserving all existing functionality.\ No newline at end of filediff --git a/browser_use/agent/message_manager/service.py b/browser_use/agent/message_manager/service.pyindex a9f225f6e..969841407 100644--- a/browser_use/agent/message_manager/service.py+++ b/browser_use/agent/message_manager/service.py@@ -120,7 +120,7 @@ class MessageManager:self.state = stateself.system_prompt = system_messageself.file_system = file_system- self.agent_history_description = '<s>Agent initialized</system>\n'+ self.agent_history_description = '<s>Agent initialized</s>\n'self.read_state_description = ''self.sensitive_data_description = ''self.available_file_paths = available_file_paths@@ -167,7 +167,9 @@ class MessageManager:# Add thinking field only if use_thinking is Trueif self.use_thinking:- example_content['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.+ example_content[+ '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.diff --git a/browser_use/agent/prompts.py b/browser_use/agent/prompts.pyindex 517422e29..40885f43d 100644--- a/browser_use/agent/prompts.py+++ b/browser_use/agent/prompts.py@@ -39,7 +39,7 @@ class SystemPrompt:try:# Choose the appropriate template based on use_thinking settingtemplate_filename = 'system_prompt.md' if self.use_thinking else 'system_prompt_no_thinking.md'-+# This works both in development and when installed as a packagewith importlib.resources.files('browser_use.agent').joinpath(template_filename).open('r', encoding='utf-8') as f:self.prompt_template = f.read()diff --git a/browser_use/agent/system_prompt.md b/browser_use/agent/system_prompt.mdindex ee9350cc9..1643a5240 100644--- a/browser_use/agent/system_prompt.md+++ b/browser_use/agent/system_prompt.md@@ -159,4 +159,4 @@ You must ALWAYS respond with a valid JSON in this exact format:}}Action list should NEVER be empty.-</output>\ No newline at end of file+</output>diff --git a/browser_use/agent/system_prompt_no_thinking.md b/browser_use/agent/system_prompt_no_thinking.mdindex 9023a744b..ac29b3c78 100644--- a/browser_use/agent/system_prompt_no_thinking.md+++ b/browser_use/agent/system_prompt_no_thinking.md@@ -156,4 +156,4 @@ You must ALWAYS respond with a valid JSON in this exact format:}}Action list should NEVER be empty.-</output>\ No newline at end of file+</output>diff --git a/browser_use/agent/views.py b/browser_use/agent/views.pyindex 713503b5e..ac670d001 100644--- a/browser_use/agent/views.py+++ b/browser_use/agent/views.py@@ -185,13 +185,21 @@ class AgentOutput(BaseModel):@staticmethoddef type_with_custom_actions_no_thinking(custom_actions: type[ActionModel]) -> type[AgentOutput]:"""Extend actions with custom actions and exclude thinking field"""-+# Create a base model without thinkingmodel_ = create_model(- 'AgentOutputNoThinking',- evaluation_previous_goal=(str, Field(..., description='One-sentence analysis of your last action. Clearly state success, failure, or uncertain.')),+ 'AgentOutput',+ evaluation_previous_goal=(+ str,+ Field(+ ..., description='One-sentence analysis of your last action. Clearly state success, failure, or uncertain.'+ ),+ ),memory=(str, Field(..., description='1-3 sentences of specific memory of this step and overall progress.')),- next_goal=(str, Field(..., description='State the next immediate goals and actions to achieve it, in one clear sentence.')),+ next_goal=(+ str,+ Field(..., description='State the next immediate goals and actions to achieve it, in one clear sentence.'),+ ),action=(list[custom_actions],Field(..., description='List of actions to execute', json_schema_extra={'min_items': 1}),@@ -199,7 +207,7 @@ class AgentOutput(BaseModel):__module__=AgentOutput.__module__,__config__=AgentOutput.model_config,)-+# Add the current_state propertydef current_state_property(self) -> AgentBrain:"""For backward compatibility - returns an AgentBrain with the flattened properties"""@@ -209,7 +217,7 @@ class AgentOutput(BaseModel):memory=self.memory,next_goal=self.next_goal,)-+model_.current_state = property(current_state_property)model_.__doc__ = 'AgentOutput model with custom actions and no thinking field'return model_