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
Make thinking field optional in browser-use agent
Cursor Agentd57850639b97
diff --git a/THINKING_FIELD_OPTIONAL_PR_SUMMARY.md b/THINKING_FIELD_OPTIONAL_PR_SUMMARY.mdnew file mode 100644index 000000000..ba5d94e7d--- /dev/null+++ b/THINKING_FIELD_OPTIONAL_PR_SUMMARY.md@@ -0,0 +1,134 @@+# 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++### 2. Created No-Thinking System Prompt Template++**File:** `browser_use/agent/system_prompt_no_thinking.md`+- New system prompt template that excludes all references to thinking+- Simplified reasoning rules section+- Updated output format specification to exclude thinking field+- Contains all other functionality (browser rules, file system, task completion, etc.)++### 3. Updated System Prompt Loading Logic++**File:** `browser_use/agent/prompts.py`+- Added `use_thinking: bool = True` parameter to `SystemPrompt.__init__()`+- Modified `_load_prompt_template()` to load the appropriate template:+ - `system_prompt.md` when `use_thinking=True` (default)+ - `system_prompt_no_thinking.md` when `use_thinking=False`++### 4. Enhanced Agent Constructor++**File:** `browser_use/agent/service.py`+- Added `use_thinking: bool = True` parameter to `Agent.__init__()`+- Pass `use_thinking` parameter to `AgentSettings`+- Pass `use_thinking` parameter to `SystemPrompt` initialization+- Pass `use_thinking` parameter to `MessageManager` initialization++### 5. Updated Action Model Generation++**File:** `browser_use/agent/views.py`+- Added `type_with_custom_actions_no_thinking()` static method to create AgentOutput models without thinking field+- This method creates dynamic models that exclude the thinking field from the schema++**File:** `browser_use/agent/service.py`+- Updated `_setup_action_models()` and `_update_action_models_for_page()` to use appropriate model based on `use_thinking` setting++### 6. Enhanced Message Manager++**File:** `browser_use/agent/message_manager/service.py`+- Added `use_thinking: bool = True` parameter to `MessageManager.__init__()`+- Updated `_init_messages()` to provide different examples:+ - Examples with thinking field when `use_thinking=True`+ - Examples without thinking field when `use_thinking=False`++### 7. Updated Logging and Serialization++**File:** `browser_use/agent/service.py`+- Modified `log_response()` function to only log thinking when present+- Updated `AgentHistory.model_dump()` to conditionally include thinking field++## Usage Examples++### With Thinking (Default Behavior)+```python+from browser_use import Agent+from browser_use.llm import ChatOpenAI++agent = Agent(+ task="Navigate to GitHub and find trending repositories",+ llm=ChatOpenAI(model="gpt-4o"),+ use_thinking=True # or omit (default)+)+```++Output includes detailed reasoning:+```json+{+ "thinking": "I need to navigate to GitHub and look for trending repositories...",+ "evaluation_previous_goal": "Successfully loaded GitHub homepage",+ "memory": "On GitHub homepage, ready to find trending repos",+ "next_goal": "Click on 'Explore' to find trending repositories",+ "action": [{"click_element_by_index": {"index": 4}}]+}+```++### Without Thinking (New Feature)+```python+from browser_use import Agent+from browser_use.llm import ChatOpenAI++agent = Agent(+ task="Navigate to GitHub and find trending repositories",+ llm=ChatOpenAI(model="gpt-4o"),+ use_thinking=False+)+```++Output is more concise:+```json+{+ "evaluation_previous_goal": "Successfully loaded GitHub homepage",+ "memory": "On GitHub homepage, ready to find trending repos",+ "next_goal": "Click on 'Explore' to find trending repositories",+ "action": [{"click_element_by_index": {"index": 4}}]+}+```++## Benefits++1. **Token Efficiency**: Reduces token usage when detailed reasoning is not needed+2. **Faster Processing**: Smaller output means faster model responses+3. **Cleaner Output**: More focused output for production use cases+4. **Backward Compatibility**: Default behavior remains unchanged+5. **Flexible Configuration**: Easy to toggle based on requirements++## Testing++The implementation maintains backward compatibility:+- Default behavior (`use_thinking=True`) works exactly as before+- All existing tests should pass without modification+- New functionality can be tested by setting `use_thinking=False`++## Technical Details++The implementation uses:+- Dynamic Pydantic model creation for structured output schemas+- Template-based system prompt selection+- Conditional field inclusion in serialization+- Type-safe parameter passing throughout the chain++All changes maintain the existing API while adding the new optional functionality.\ No newline at end of filediff --git a/browser_use/agent/message_manager/service.py b/browser_use/agent/message_manager/service.pyindex aea09d4b2..f4b769d35 100644--- a/browser_use/agent/message_manager/service.py+++ b/browser_use/agent/message_manager/service.py@@ -113,16 +113,18 @@ class MessageManager:available_file_paths: list[str] | None = None,settings: MessageManagerSettings = MessageManagerSettings(),state: MessageManagerState = MessageManagerState(),+ use_thinking: bool = True,):self.task = taskself.settings = settingsself.state = stateself.system_prompt = system_messageself.file_system = file_system- self.agent_history_description = '<system>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+ self.use_thinking = use_thinking# Only initialize messages if state is emptyif len(self.state.history.messages) == 0:self._init_messages()@@ -137,24 +139,26 @@ class MessageManager:# placeholder_message = HumanMessage(content='Example output:')self._add_message_with_type(placeholder_message, message_type='init')- example_tool_call_1 = AssistantMessage(- content=json.dumps(- {- '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.+ if self.use_thinking:+ # Example with thinking field+ example_tool_call_1 = AssistantMessage(+ content=json.dumps(+ {+ '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@@ -167,25 +171,70 @@ 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,- }- },- ],- }+ }+ },+ {+ 'click_element_by_index': {+ 'index': 4,+ }+ },+ ],+ }+ ))- )+ else:+ # Example without thinking field+ example_tool_call_1 = AssistantMessage(+ content=json.dumps(+ {+ '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+- [ ] Initialize a tracking file for GitHub repositories called github.md+- [ ] Visit each Github repository and find their description+- [ ] Visit bytedance/UI-TARS-desktop+- [ ] Visit ray-project/kuberay+- [ ] Check for additional Github repositories by scrolling down+- [ ] Compile all results in the requested format+- [ ] Validate that I have not missed anything in the page+- [ ] Report final results to user+""".strip('\n'),+ }+ },+ {+ 'write_file': {+ 'path': 'github.md',+ 'content': """+# Github Repositories:+""",+ }+ },+ {+ 'click_element_by_index': {+ 'index': 4,+ }+ },+ ],+ }+ )+ )+self._add_message_with_type(example_tool_call_1, message_type='init')self._add_message_with_type(UserMessage(diff --git a/browser_use/agent/prompts.py b/browser_use/agent/prompts.pyindex 3fb26d580..517422e29 100644--- a/browser_use/agent/prompts.py+++ b/browser_use/agent/prompts.py@@ -17,9 +17,11 @@ class SystemPrompt:max_actions_per_step: int = 10,override_system_message: str | None = None,extend_system_message: str | None = None,+ use_thinking: bool = True,):self.default_action_description = action_descriptionself.max_actions_per_step = max_actions_per_step+ self.use_thinking = use_thinkingprompt = ''if override_system_message:prompt = override_system_message@@ -35,8 +37,11 @@ class SystemPrompt:def _load_prompt_template(self) -> None:"""Load the prompt template from the markdown file."""try:+ # Choose the appropriate template based on use_thinking setting+ template_filename = 'system_prompt.md' if self.use_thinking else 'system_prompt_no_thinking.md'+# This works both in development and when installed as a package- with importlib.resources.files('browser_use.agent').joinpath('system_prompt.md').open('r', encoding='utf-8') as f:+ with importlib.resources.files('browser_use.agent').joinpath(template_filename).open('r', encoding='utf-8') as f:self.prompt_template = f.read()except Exception as e:raise RuntimeError(f'Failed to load system prompt template: {e}')diff --git a/browser_use/agent/service.py b/browser_use/agent/service.pyindex 38de6a6cb..bd5f53ba1 100644--- a/browser_use/agent/service.py+++ b/browser_use/agent/service.py@@ -94,7 +94,9 @@ def log_response(response: AgentOutput, registry=None, logger=None) -> None:else:emoji = '❔'- logger.info(f'💡 Thinking:\n{response.current_state.thinking}')+ # Only log thinking if it's present+ if response.current_state.thinking:+ logger.info(f'💡 Thinking:\n{response.current_state.thinking}')logger.info(f'{emoji} Eval: {response.current_state.evaluation_previous_goal}')logger.info(f'🧠 Memory: {response.current_state.memory}')logger.info(f'🎯 Next goal: {response.current_state.next_goal}\n')@@ -165,6 +167,7 @@ class Agent(Generic[Context]):'aria-checked',],max_actions_per_step: int = 1,+ use_thinking: bool = True,page_extraction_llm: BaseChatModel | None = None,planner_llm: BaseChatModel | None = None,planner_interval: int = 1, # Run planner every N steps@@ -217,6 +220,7 @@ class Agent(Generic[Context]):planner_interval=planner_interval,is_planner_reasoning=is_planner_reasoning,extend_planner_system_message=extend_planner_system_message,+ use_thinking=use_thinking,)# Token cost service@@ -288,6 +292,7 @@ class Agent(Generic[Context]):max_actions_per_step=self.settings.max_actions_per_step,override_system_message=override_system_message,extend_system_message=extend_system_message,+ use_thinking=self.settings.use_thinking,).get_system_message(),file_system=self.file_system,settings=MessageManagerSettings(@@ -298,6 +303,7 @@ class Agent(Generic[Context]):),available_file_paths=self.settings.available_file_paths,state=self.state.message_manager_state,+ use_thinking=self.settings.use_thinking,)# TODO: FIX MEMORY@@ -605,11 +611,17 @@ class Agent(Generic[Context]):# Initially only include actions with no filtersself.ActionModel = self.controller.registry.create_action_model()# Create output model with the dynamic actions- self.AgentOutput = AgentOutput.type_with_custom_actions(self.ActionModel)+ if self.settings.use_thinking:+ self.AgentOutput = AgentOutput.type_with_custom_actions(self.ActionModel)+ else:+ self.AgentOutput = AgentOutput.type_with_custom_actions_no_thinking(self.ActionModel)# used to force the done action when max_steps is reachedself.DoneActionModel = self.controller.registry.create_action_model(include_actions=['done'])- self.DoneAgentOutput = AgentOutput.type_with_custom_actions(self.DoneActionModel)+ if self.settings.use_thinking:+ self.DoneAgentOutput = AgentOutput.type_with_custom_actions(self.DoneActionModel)+ else:+ self.DoneAgentOutput = AgentOutput.type_with_custom_actions_no_thinking(self.DoneActionModel)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"""@@ -1299,20 +1311,6 @@ class Agent(Generic[Context]):)break- new_path_hashes = {e.hash.branch_path_hash for e in new_selector_map.values()}- if check_for_new_elements and not new_path_hashes.issubset(cached_path_hashes):- # next action requires index but there are new elements on the page- msg = 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,- )- )- break-try:await self._raise_if_stopped_or_paused()@@ -1665,8 +1663,14 @@ class Agent(Generic[Context]):# Create new action model with current page's filtered actionsself.ActionModel = self.controller.registry.create_action_model(page=page)# Update output model with the new actions- self.AgentOutput = AgentOutput.type_with_custom_actions(self.ActionModel)+ if self.settings.use_thinking:+ self.AgentOutput = AgentOutput.type_with_custom_actions(self.ActionModel)+ else:+ self.AgentOutput = AgentOutput.type_with_custom_actions_no_thinking(self.ActionModel)# Update done action model tooself.DoneActionModel = self.controller.registry.create_action_model(include_actions=['done'], page=page)- self.DoneAgentOutput = AgentOutput.type_with_custom_actions(self.DoneActionModel)+ if self.settings.use_thinking:+ self.DoneAgentOutput = AgentOutput.type_with_custom_actions(self.DoneActionModel)+ else:+ self.DoneAgentOutput = AgentOutput.type_with_custom_actions_no_thinking(self.DoneActionModel)diff --git a/browser_use/agent/system_prompt_no_thinking.md b/browser_use/agent/system_prompt_no_thinking.mdnew file mode 100644index 000000000..9830d12df--- /dev/null+++ b/browser_use/agent/system_prompt_no_thinking.md@@ -0,0 +1,159 @@+You are an AI agent designed to operate in an iterative loop to automate browser tasks. Your ultimate goal is accomplishing the task provided in <user_request>.++<intro>+You excel at following tasks:+1. Navigating complex websites and extracting precise information+2. Automating form submissions and interactive web actions+3. Gathering and saving information+4. Using your filesystem effectively to decide what to keep in your context+5. Operate effectively in an agent loop+6. Efficiently performing diverse web tasks+</intro>++<language_settings>+- Default working language: **English**+- Use the language specified by user in messages as the working language+</language_settings>++<input>+At every step, your input will consist of:+1. <agent_history>: A chronological event stream including your previous actions and their results.+2. <agent_state>: Current <user_request>, summary of <file_system>, <todo_contents>, and <step_info>.+3. <browser_state>: Current URL, open tabs, interactive elements indexed for actions, and visible page content.+4. <browser_vision>: Screenshot of the browser with bounding boxes around interactive elements.+5. <read_state> This will be displayed only if your previous action was extract_structured_data or read_file. This data is only shown in the current step.+</input>++<agent_history>+Agent history will be given as a list of step information as follows:++<step_{{step_number}}>:+Evaluation of Previous Step: Assessment of last action+Memory: Your memory of this step+Next Goal: Your goal for this step+Action Results: Your actions and their results+</step_{{step_number}}>++and system messages wrapped in <s> tag.+</agent_history>++<user_request>+USER REQUEST: This is your ultimate objective and always remains visible.+- This has the highest priority. Make the user happy.+- If the user request is very specific - then carefully follow each step and dont skip or hallucinate steps.+- If the task is open ended you can plan yourself how to get it done.+</user_request>++<browser_state>+1. Browser State will be given as:++Current URL: URL of the page you are currently viewing.+Open Tabs: Open tabs with their indexes.+Interactive Elements: All interactive elements will be provided in format as [index]<type>text</type> where+- index: Numeric identifier for interaction+- type: HTML element type (button, input, etc.)+- text: Element description++Examples:+[33]<div>User form</div>+\t*[35]*<button aria-label='Submit form'>Submit</button>++Note that:+- Only elements with numeric indexes in [] are interactive+- (stacked) indentation (with \t) is important and means that the element is a (html) child of the element above (with a lower index)+- Elements with \* are new elements that were added after the previous step (if url has not changed)+- Pure text elements without [] are not interactive.+</browser_state>++<browser_vision>+You will be optionally provided with a screenshot of the browser with bounding boxes. This is your GROUND TRUTH: analyze the image to evaluate your progress.+Bounding box labels correspond to element indexes - analyze the image to make sure you click on correct elements.+</browser_vision>++<browser_rules>+Strictly follow these rules while using the browser and navigating the web:+- Only interact with elements that have a numeric [index] assigned.+- Only use indexes that are explicitly provided.+- If research is needed, use "open_tab" tool to open a **new tab** instead of reusing the current one.+- If the page changes after, for example, an input text action, analyse if you need to interact with new elements, e.g. selecting the right option from the list.+- By default, only elements in the visible viewport are listed. Use scrolling tools if you suspect relevant content is offscreen which you need to interact with. Scroll ONLY if there are more pixels below or above the page. The extract content action gets the full loaded page content.+- If a captcha appears, attempt solving it if possible. If not, use fallback strategies (e.g., alternative site, backtrack).+- If expected elements are missing, try refreshing, scrolling, or navigating back.+- If the page is not fully loaded, use the wait action.+- You can call extract_structured_data on specific pages to gather structured semantic information from the entire page, including parts not currently visible. If you see results in your read state, these are displayed only once, so make sure to save them if necessary.+- Call extract_structured_data only if the relevant information is not visible in your <browser_state>.+- If you fill an input field and your action sequence is interrupted, most often something changed e.g. suggestions popped up under the field.+- If the <user_request> includes specific page information such as product type, rating, price, location, etc., try to apply filters to be more efficient.+- The <user_request> is the ultimate goal. If the user specifies explicit steps, they have always the highest priority.+- If you input_text into a field, you might need to press enter, click the search button, or select from dropdown for completion.+</browser_rules>++<file_system>+- You have access to a persistent file system which you can use to track progress, store results, and manage long tasks.+- Your file system is initialized with two files:+ 1. `todo.md`: Use this to keep a checklist for known subtasks. Update it to mark completed items and track what remains. This file should guide your step-by-step execution when the task involves multiple known entities (e.g., a list of links or items to visit). The contents of this file will be also visible in your state. ALWAYS use `write_file` to rewrite entire `todo.md` when you want to update your progress. NEVER use `append_file` on `todo.md` as this can explode your context.+ 2. `results.md`: Use this to accumulate extracted or generated results for the user. Append each new finding clearly and avoid duplication. This file serves as your output log.+- You can read, write, and append to files.+- Note that `write_file` overwrites the entire file, use it with care on existing files.+- When you `append_file`, ALWAYS put newlines in the beginning and not at the end.+- If the file is too large, you are only given a preview of your file. Use read_file to see the full content if necessary.+- Always use the file system as the source of truth. Do not rely on memory alone for tracking task state.+- If exists, <available_file_paths> includes files you have downloaded or uploaded by the user. You can only read or upload these files but you don't have write access.+</file_system>++<task_completion_rules>+You must call the `done` action in one of two cases:+- When you have fully completed the USER REQUEST.+- When you reach the final allowed step (`max_steps`), even if the task is incomplete.+- If it is ABSOLUTELY IMPOSSIBLE to continue.++The `done` action is your opportunity to terminate and share your findings with the user.+- Set `success` to `true` only if the full USER REQUEST has been completed with no missing components.+- If any part of the request is missing, incomplete, or uncertain, set `success` to `false`.+- You can use the `text` field of the `done` action to communicate your findings and `files_to_display` to send file attachments to the user, e.g. `["results.md"]`.+- Combine `text` and `files_to_display` to provide a coherent reply to the user and fulfill the USER REQUEST.+- You are ONLY ALLOWED to call `done` as a single action. Don't call it together with other actions.+- If the user asks for specified format, such as "return JSON with following structure", "return a list of format...", MAKE sure to use the right format in your answer.+</task_completion_rules>++<action_rules>+- You are allowed to use a maximum of {max_actions} actions per step.++If you are allowed multiple actions:+- You can specify multiple actions in the list to be executed sequentially (one after another).+- If the page changes after an action, the sequence is interrupted and you get the new state. You can see this in your agent history when this happens.+- At every step, use ONLY ONE action to interact with the browser. DO NOT use multiple browser actions as your actions can change the browser state.++If you are allowed 1 action, ALWAYS output only the most reasonable action per step.+</action_rules>++<reasoning_rules>+Be clear and concise in your decision-making:+- Analyze <agent_history> to track progress and context toward <user_request>.+- Analyze the most recent "Next Goal" and "Action Result" in <agent_history> and clearly state what you previously tried to achieve.+- Analyze all relevant items in <agent_history>, <browser_state>, <read_state>, <file_system>, <read_state> and the screenshot to understand your state.+- Explicitly judge success/failure/uncertainty of the last action.+- If todo.md is empty and the task is multi-step, generate a stepwise plan in todo.md using file tools.+- Analyze `todo.md` to guide and track your progress.+- If any todo.md items are finished, mark them as complete in the file.+- Analyze whether you are stuck in the same goal for a few steps. If so, try alternative methods.+- Analyze the <read_state> where one-time information are displayed due to your previous action. Decide whether you want to keep this information in memory and plan writing them into a file if applicable using the file tools.+- If you see information relevant to <user_request>, plan saving the information into a file.+- Before writing data into a file, analyze the <file_system> and check if the file already has some content to avoid overwriting.+- Decide what concise, actionable context should be stored in memory to inform future reasoning.+- When ready to finish, state you are preparing to call done and communicate completion/results to the user.+- Before done, use read_file to verify file contents intended for user output.+</reasoning_rules>++<o>+You must ALWAYS respond with a valid JSON in this exact format:++{{+ "evaluation_previous_goal": "One-sentence analysis of your last action. Clearly state success, failure, or uncertain.",+ "memory": "1-3 sentences of specific memory of this step and overall progress. You should put here everything that will help you track progress in future steps. Like counting pages visited, items found, etc.",+ "next_goal": "State the next immediate goals and actions to achieve it, in one clear sentence."+ "action":[{{"one_action_name": {{// action-specific parameter}}}}, // ... more actions in sequence]+}}++Action list should NEVER be empty.+</o>\ No newline at end of filediff --git a/browser_use/agent/views.py b/browser_use/agent/views.pyindex 1e39bf4f0..713503b5e 100644--- a/browser_use/agent/views.py+++ b/browser_use/agent/views.py@@ -50,6 +50,7 @@ class AgentSettings(BaseModel):'aria-expanded',]max_actions_per_step: int = 10+ use_thinking: bool = Truepage_extraction_llm: BaseChatModel | None = Noneplanner_llm: BaseChatModel | None = None@@ -137,7 +138,7 @@ class StepMetadata(BaseModel):class AgentBrain(BaseModel):- thinking: str+ thinking: str | None = Noneevaluation_previous_goal: strmemory: strnext_goal: str@@ -146,7 +147,7 @@ class AgentBrain(BaseModel):class AgentOutput(BaseModel):model_config = ConfigDict(arbitrary_types_allowed=True, extra='forbid')- thinking: str+ thinking: str | None = Noneevaluation_previous_goal: strmemory: strnext_goal: str@@ -181,6 +182,38 @@ class AgentOutput(BaseModel):model_.__doc__ = 'AgentOutput model with custom actions'return model_+ @staticmethod+ def 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 thinking+ model_ = create_model(+ 'AgentOutputNoThinking',+ 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.')),+ action=(+ list[custom_actions],+ Field(..., description='List of actions to execute', json_schema_extra={'min_items': 1}),+ ),+ __module__=AgentOutput.__module__,+ __config__=AgentOutput.model_config,+ )++ # Add the current_state property+ def current_state_property(self) -> AgentBrain:+ """For backward compatibility - returns an AgentBrain with the flattened properties"""+ return AgentBrain(+ thinking=None,+ evaluation_previous_goal=self.evaluation_previous_goal,+ 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_+class AgentHistory(BaseModel):"""History item for agent actions"""@@ -212,12 +245,14 @@ class AgentHistory(BaseModel):if self.model_output:action_dump = [action.model_dump(exclude_none=True) for action in self.model_output.action]model_output_dump = {- 'thinking': self.model_output.thinking,'evaluation_previous_goal': self.model_output.evaluation_previous_goal,'memory': self.model_output.memory,'next_goal': self.model_output.next_goal,'action': action_dump, # This preserves the actual action data}+ # Only include thinking if it's present+ if self.model_output.thinking is not None:+ model_output_dump['thinking'] = self.model_output.thinkingreturn {'model_output': model_output_dump,