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
Enhance agent task completion and max steps handling
Magnus Müllerd881b9f61d8a
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.pyindex 2a8b66b2d..40664ab82 100644--- a/browser_use/agent/service.py+++ b/browser_use/agent/service.py@@ -278,6 +278,10 @@ class Agent(Generic[Context]):# Create output model with the dynamic actionsself.AgentOutput = AgentOutput.type_with_custom_actions(self.ActionModel)+ # used to force the done action when max_steps is reached+ self.DoneActionModel = self.controller.registry.create_action_model(include_actions=['done'])+ self.DoneAgentOutput = AgentOutput.type_with_custom_actions(self.DoneActionModel)+def set_tool_calling_method(self, tool_calling_method: Optional[ToolCallingMethod]) -> Optional[ToolCallingMethod]:if tool_calling_method == 'auto':if self.chat_model_library == 'ChatGoogleGenerativeAI':@@ -334,6 +338,9 @@ class Agent(Generic[Context]):msg = 'Now comes your last step. You have to use the done action now! Provide your best result of the ultimate task given your findings inside the done action.'logger.info('Last step finishing up')self._message_manager._add_message_with_tokens(HumanMessage(content=msg), position=-1)+ entire_output_model = self.AgentOutput+ self.AgentOutput = self.DoneAgentOutput+input_messages = self._message_manager.get_messages()tokens = self._message_manager.state.history.current_tokens@@ -534,7 +541,11 @@ class Agent(Generic[Context]):if not await self._validate_output():return True, False- logger.info('✅ Task completed successfully')+ logger.info('✅ Task completed')+ if self.state.history.is_successful():+ logger.info('✅ Successfully')+ else:+ logger.info('❌ Unfinished')if self.register_done_callback:await self.register_done_callback(self.state.history)@@ -579,7 +590,12 @@ class Agent(Generic[Context]):if not await self._validate_output():continue- logger.info('✅ Task completed successfully')+ logger.info('✅ Task completed')+ if self.state.history.is_successful():+ logger.info('✅ Successfully')+ else:+ logger.info('❌ Unfinished')+if self.register_done_callback:await self.register_done_callback(self.state.history)breakdiff --git a/browser_use/agent/system_prompt.md b/browser_use/agent/system_prompt.mdindex d9779886e..4d9b321c9 100644--- a/browser_use/agent/system_prompt.md+++ b/browser_use/agent/system_prompt.md@@ -1,4 +1,5 @@You are an AI agent designed to automate browser tasks. Your goal is to accomplish the ultimate task following the rules.+# Input FormatTaskPrevious steps@@ -14,12 +15,14 @@ Example:- Only elements with numeric indexes in [] are interactive- elements without [] provide only context+# Response Rules1. RESPONSE FORMAT: You must ALWAYS respond with valid JSON in this exact format:{{"current_state": {{"evaluation_previous_goal": "Success|Failed|Unknown - Analyze the current elements and the image to check if the previous goals/actions are successful like intended by the task. Mention if something unexpected happened. Shortly state why/why not","memory": "Description of what has been done and what you need to remember. Be very specific. Count here ALWAYS how many times you have done something and how many remain. E.g. 0 out of 10 websites analyzed. Continue with abc and xyz","next_goal": "What needs to be done with the next immediate action"}},"action":[{{"one_action_name": {{// action-specific parameter}}}}, // ... more actions in sequence]}}+2. ACTIONS: You can specify multiple actions in the list to be executed in sequence. But always specify only one action name per item. Use maximum {{max_actions}} actions per sequence.Common action sequences:- Form filling: [{{"input_text": {{"index": 1, "text": "username"}}}}, {{"input_text": {{"index": 2, "text": "password"}}}}, {{"click_element": {{"index": 3}}}}]@@ -29,9 +32,11 @@ Common action sequences:- Only provide the action sequence until an action which changes the page state significantly.- Try to be efficient, e.g. fill forms at once, or chain actions where nothing changes on the page- only use multiple actions if it makes sense.+3. ELEMENT INTERACTION:- Only use indexes of the interactive elements- Elements marked with "[]Non-interactive text" are non-interactive+4. NAVIGATION & ERROR HANDLING:- If no suitable elements exist, use other functions to complete the task- If stuck, try alternative approaches - like going back to a previous page, new search, new tab etc.@@ -40,19 +45,25 @@ Common action sequences:- If you want to research something, open a new tab instead of using the current tab- If captcha pops up, try to solve it - else try a different approach- If the page is not fully loaded, use wait action+5. TASK COMPLETION:- Use the done action as the last action as soon as the ultimate task is complete-- Dont use "done" before you are done with everything the user asked you.+- Dont use "done" before you are done with everything the user asked you, except you reach the last step of max_steps.+- If you reach the max_steps, use the done action even you are not finished and provide all the information you have gathered so far.- If you have to do something repeatedly for example the task says for "each", or "for all", or "x times", count always inside "memory" how many times you have done it and how many remain. Don't stop until you have completed like the task asked you. Only call done after the last step.- Don't hallucinate actions- Make sure to include everything the user asked for in the done text parameter. This is what the user will see. Do not just say you are done, but include the requested information of the task.+6. VISUAL CONTEXT:- When an image is provided, use it to understand the page layout- Bounding boxes with labels on their top right corner correspond to element indexes+7. Form filling:- If you fill an input field and your action sequence is interrupted, most often something changed e.g. suggestions popped up under the field.+8. Long tasks:- Keep track of the status and subresults in the memory.+9. Extraction:- If your task is to find information - call extract_content on the specific pages to get and store the information.Your responses must be always JSON with the specified format.\ No newline at end of filediff --git a/browser_use/controller/registry/service.py b/browser_use/controller/registry/service.pyindex 192b9b03d..20d80f189 100644--- a/browser_use/controller/registry/service.py+++ b/browser_use/controller/registry/service.py@@ -171,7 +171,7 @@ class Registry(Generic[Context]):return params@time_execution_sync('--create_action_model')- def create_action_model(self) -> Type[ActionModel]:+ def create_action_model(self, include_actions: Optional[list[str]] = None) -> Type[ActionModel]:"""Creates a Pydantic model from registered actions"""fields = {name: (@@ -179,6 +179,7 @@ class Registry(Generic[Context]):Field(default=None, description=action.description),)for name, action in self.registry.actions.items()+ if include_actions is None or name in include_actions}self.telemetry.capture(@@ -186,6 +187,7 @@ class Registry(Generic[Context]):registered_functions=[RegisteredFunction(name=name, params=action.param_model.model_json_schema())for name, action in self.registry.actions.items()+ if include_actions is None or name in include_actions]))