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
dynamic planing exploration
Saurav Panda4a522a6f1c77
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.pyindex 7250106ab..01caacfff 100644--- a/browser_use/agent/service.py+++ b/browser_use/agent/service.py@@ -57,7 +57,7 @@ from browser_use.agent.views import (BrowserStateHistory,DetectedVariable,JudgementResult,- PlanStep,+ PlanItem,StepMetadata,)from browser_use.browser.events import _get_timeout@@ -197,6 +197,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):final_response_after_failure: bool = True,enable_planning: bool = True,planning_replan_on_stall: int = 3,+ planning_exploration_limit: int = 5,llm_screenshot_size: tuple[int, int] | None = None,_url_shortening_limit: int = 25,**kwargs,@@ -392,6 +393,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):ground_truth=ground_truth,enable_planning=enable_planning,planning_replan_on_stall=planning_replan_on_stall,+ planning_exploration_limit=planning_exploration_limit,)# Token cost service@@ -1074,6 +1076,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):await self._inject_budget_warning(step_info)self._inject_replan_nudge()+ self._inject_exploration_nudge()await self._force_done_after_last_step(step_info)await self._force_done_after_failure()return browser_state_summary@@ -1251,14 +1254,14 @@ class Agent(Generic[Context, AgentStructuredOutput]):self.state.n_steps += 1def _update_plan_from_model_output(self, model_output: AgentOutput) -> None:- """Update the plan state from model output fields (current_plan_step, plan_update)."""+ """Update the plan state from model output fields (current_plan_item, plan_update)."""if not self.settings.enable_planning:return# If model provided a new plan via plan_update, replace the current planif model_output.plan_update is not None:- self.state.plan = [PlanStep(text=step_text) for step_text in model_output.plan_update]- self.state.current_plan_step_index = 0+ self.state.plan = [PlanItem(text=step_text) for step_text in model_output.plan_update]+ self.state.current_plan_item_index = 0self.state.plan_generation_step = self.state.n_stepsif self.state.plan:self.state.plan[0].status = 'current'@@ -1268,11 +1271,11 @@ class Agent(Generic[Context, AgentStructuredOutput]):return# If model provided a step index update, advance the plan- if model_output.current_plan_step is not None and self.state.plan is not None:- new_idx = model_output.current_plan_step+ if model_output.current_plan_item is not None and self.state.plan is not None:+ new_idx = model_output.current_plan_item# Clamp to valid rangenew_idx = max(0, min(new_idx, len(self.state.plan) - 1))- old_idx = self.state.current_plan_step_index+ old_idx = self.state.current_plan_item_index# Mark steps between old and new as donefor i in range(old_idx, new_idx):@@ -1283,7 +1286,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):if new_idx < len(self.state.plan):self.state.plan[new_idx].status = 'current'- self.state.current_plan_step_index = new_idx+ self.state.current_plan_item_index = new_idxdef _render_plan_description(self) -> str | None:"""Render the current plan as a text description for injection into agent context."""@@ -1313,6 +1316,22 @@ class Agent(Generic[Context, AgentStructuredOutput]):self.logger.info(f'📋 Replan nudge injected after {self.state.consecutive_failures} consecutive failures')self._message_manager._add_context_message(UserMessage(content=msg))+ def _inject_exploration_nudge(self) -> None:+ """Nudge the agent to create a plan (or call done) after exploring without one."""+ if not self.settings.enable_planning or self.state.plan is not None:+ return+ if self.settings.planning_exploration_limit <= 0:+ return+ if self.state.n_steps >= self.settings.planning_exploration_limit:+ msg = (+ 'PLANNING NUDGE: You have taken '+ f'{self.state.n_steps} steps without creating a plan. '+ 'If the task is complex, output a `plan_update` with clear todo items now. '+ 'If the task is already done or nearly done, call `done` instead.'+ )+ self.logger.info(f'📋 Exploration nudge injected after {self.state.n_steps} steps without a plan')+ self._message_manager._add_context_message(UserMessage(content=msg))+async def _inject_budget_warning(self, step_info: AgentStepInfo | None = None) -> None:"""Inject a prominent budget warning when the agent has used >= 75% of its step budget.diff --git a/browser_use/agent/system_prompts/system_prompt.md b/browser_use/agent/system_prompts/system_prompt.mdindex b11de1a85..8d30e5abd 100644--- a/browser_use/agent/system_prompts/system_prompt.md+++ b/browser_use/agent/system_prompts/system_prompt.md@@ -100,12 +100,14 @@ Strictly follow these rules while using the browser and navigating the web:- DO NOT use the file system if the task is less than 10 steps!</file_system><planning>-On your FIRST step, create a high-level plan by outputting `plan_update` with 3-10 steps.-On subsequent steps, `<plan>` in your input shows the current plan with status markers:- [x]=done, [>]=current, [ ]=pending, [-]=skipped-Output `current_plan_step` (0-indexed integer) to indicate which step you are working on now.-Only output `plan_update` again if the plan needs significant revision (e.g. after unexpected obstacles).-Completing all plan steps does NOT mean the task is done. Always verify against the original <user_request> before calling `done`. If the plan was insufficient, output a new `plan_update` with additional steps rather than calling `done` early.+Decide whether to plan based on task complexity:+- Simple task (1-3 actions, e.g. "go to X and click Y"): Act directly. Do NOT output `plan_update`.+- Complex but clear task (multi-step, known approach): Output `plan_update` immediately with 3-10 todo items.+- Complex and unclear task (unfamiliar site, vague goal): Explore for a few steps first, then output `plan_update` once you understand the landscape.+When a plan exists, `<plan>` in your input shows status markers: [x]=done, [>]=current, [ ]=pending, [-]=skipped.+Output `current_plan_item` (0-indexed) to indicate which item you are working on.+Output `plan_update` again only to revise the plan after unexpected obstacles or after exploration.+Completing all plan items does NOT mean the task is done. Always verify against the original <user_request> before calling `done`.</planning><task_completion_rules>You must call the `done` action in one of two cases:@@ -204,12 +206,12 @@ You must ALWAYS respond with a valid JSON in this exact format:"evaluation_previous_goal": "Concise 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 goal and action to achieve it, in one clear sentence.",- "current_plan_step": 0,- "plan_update": ["Step 1 description", "Step 2 description"],+ "current_plan_item": 0,+ "plan_update": ["Todo item 1", "Todo item 2", "Todo item 3"],"action":[{{"navigate": {{ "url": "url_value"}}}}, // ... more actions in sequence]}}Action list should NEVER be empty.-`current_plan_step` and `plan_update` are optional. See <planning> for details.+`current_plan_item` and `plan_update` are optional. See <planning> for details.</output><critical_reminders>1. ALWAYS verify action success using the screenshot before proceedingdiff --git a/browser_use/agent/system_prompts/system_prompt_no_thinking.md b/browser_use/agent/system_prompts/system_prompt_no_thinking.mdindex 7b1d211a7..39240ed81 100644--- a/browser_use/agent/system_prompts/system_prompt_no_thinking.md+++ b/browser_use/agent/system_prompts/system_prompt_no_thinking.md@@ -97,12 +97,14 @@ Strictly follow these rules while using the browser and navigating the web:- DO NOT use the file system if the task is less than 10 steps!</file_system><planning>-On your FIRST step, create a high-level plan by outputting `plan_update` with 3-10 steps.-On subsequent steps, `<plan>` in your input shows the current plan with status markers:- [x]=done, [>]=current, [ ]=pending, [-]=skipped-Output `current_plan_step` (0-indexed integer) to indicate which step you are working on now.-Only output `plan_update` again if the plan needs significant revision (e.g. after unexpected obstacles).-Completing all plan steps does NOT mean the task is done. Always verify against the original <user_request> before calling `done`. If the plan was insufficient, output a new `plan_update` with additional steps rather than calling `done` early.+Decide whether to plan based on task complexity:+- Simple task (1-3 actions, e.g. "go to X and click Y"): Act directly. Do NOT output `plan_update`.+- Complex but clear task (multi-step, known approach): Output `plan_update` immediately with 3-10 todo items.+- Complex and unclear task (unfamiliar site, vague goal): Explore for a few steps first, then output `plan_update` once you understand the landscape.+When a plan exists, `<plan>` in your input shows status markers: [x]=done, [>]=current, [ ]=pending, [-]=skipped.+Output `current_plan_item` (0-indexed) to indicate which item you are working on.+Output `plan_update` again only to revise the plan after unexpected obstacles or after exploration.+Completing all plan items does NOT mean the task is done. Always verify against the original <user_request> before calling `done`.</planning><task_completion_rules>You must call the `done` action in one of two cases:@@ -194,12 +196,12 @@ 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 goal and action to achieve it, in one clear sentence.",- "current_plan_step": 0,- "plan_update": ["Step 1 description", "Step 2 description"],+ "current_plan_item": 0,+ "plan_update": ["Todo item 1", "Todo item 2", "Todo item 3"],"action":[{{"navigate": {{ "url": "url_value"}}}}, // ... more actions in sequence]}}Action list should NEVER be empty.-`current_plan_step` and `plan_update` are optional. See <planning> for details.+`current_plan_item` and `plan_update` are optional. See <planning> for details.</output><critical_reminders>1. ALWAYS verify action success using the screenshot before proceedingdiff --git a/browser_use/agent/views.py b/browser_use/agent/views.pyindex d77db32b8..d51239ba6 100644--- a/browser_use/agent/views.py+++ b/browser_use/agent/views.py@@ -49,6 +49,7 @@ class AgentSettings(BaseModel):max_history_items: int | None = Noneenable_planning: bool = Trueplanning_replan_on_stall: int = 3 # consecutive failures before replan nudge; 0 = disabled+ planning_exploration_limit: int = 5 # steps without a plan before nudge; 0 = disabledpage_extraction_llm: BaseChatModel | None = Nonecalculate_cost: bool = False@@ -67,8 +68,8 @@ class AgentState(BaseModel):n_steps: int = 1consecutive_failures: int = 0last_result: list[ActionResult] | None = None- plan: list[PlanStep] | None = None- current_plan_step_index: int = 0+ plan: list[PlanItem] | None = None+ current_plan_item_index: int = 0plan_generation_step: int | None = Nonelast_model_output: AgentOutput | None = None@@ -180,7 +181,7 @@ class StepMetadata(BaseModel):return self.step_end_time - self.step_start_time-class PlanStep(BaseModel):+class PlanItem(BaseModel):text: strstatus: Literal['pending', 'current', 'done', 'skipped'] = 'pending'@@ -199,7 +200,7 @@ class AgentOutput(BaseModel):evaluation_previous_goal: str | None = Nonememory: str | None = Nonenext_goal: str | None = None- current_plan_step: int | None = None+ current_plan_item: int | None = Noneplan_update: list[str] | None = Noneaction: list[ActionModel] = Field(...,@@ -273,7 +274,7 @@ class AgentOutput(BaseModel):del schema['properties']['thinking']del schema['properties']['evaluation_previous_goal']del schema['properties']['next_goal']- schema['properties'].pop('current_plan_step', None)+ schema['properties'].pop('current_plan_item', None)schema['properties'].pop('plan_update', None)# Update required fields to only include remaining propertiesschema['required'] = ['memory', 'action']@@ -394,8 +395,8 @@ class AgentHistory(BaseModel):# Only include thinking if it's presentif self.model_output.thinking is not None:model_output_dump['thinking'] = self.model_output.thinking- if self.model_output.current_plan_step is not None:- model_output_dump['current_plan_step'] = self.model_output.current_plan_step+ if self.model_output.current_plan_item is not None:+ model_output_dump['current_plan_item'] = self.model_output.current_plan_itemif self.model_output.plan_update is not None:model_output_dump['plan_update'] = self.model_output.plan_updatediff --git a/tests/ci/test_agent_planning.py b/tests/ci/test_agent_planning.pyindex c4db3d632..fd911846e 100644--- a/tests/ci/test_agent_planning.py+++ b/tests/ci/test_agent_planning.py@@ -8,7 +8,7 @@ import jsonfrom browser_use.agent.views import (AgentOutput,- PlanStep,+ PlanItem,)from browser_use.tools.service import Tools@@ -27,7 +27,7 @@ def _make_agent_output(**overrides) -> AgentOutput:'evaluation_previous_goal': 'Success','memory': 'mem','next_goal': 'goal',- **{k: v for k, v in overrides.items() if k in ('current_plan_step', 'plan_update')},+ **{k: v for k, v in overrides.items() if k in ('current_plan_item', 'plan_update')},'action': [{'done': {'text': 'ok', 'success': True}}],})@@ -57,12 +57,12 @@ async def test_plan_generation_from_plan_update(browser_session, mock_llm):assert agent.state.plan[0].status == 'current'assert agent.state.plan[1].status == 'pending'assert agent.state.plan[2].status == 'pending'- assert agent.state.current_plan_step_index == 0+ assert agent.state.current_plan_item_index == 0assert agent.state.plan_generation_step == agent.state.n_steps# ----------------------------------------------------------------------------# 2. Plan step advancement via current_plan_step+# 2. Plan step advancement via current_plan_item# ---------------------------------------------------------------------------@@ -70,19 +70,19 @@ async def test_plan_step_advancement(browser_session, mock_llm):agent = _make_agent(browser_session, mock_llm)# Seed a planagent.state.plan = [- PlanStep(text='Step A', status='current'),- PlanStep(text='Step B'),- PlanStep(text='Step C'),+ PlanItem(text='Step A', status='current'),+ PlanItem(text='Step B'),+ PlanItem(text='Step C'),]- agent.state.current_plan_step_index = 0+ agent.state.current_plan_item_index = 0- output = _make_agent_output(current_plan_step=2)+ output = _make_agent_output(current_plan_item=2)agent._update_plan_from_model_output(output)assert agent.state.plan[0].status == 'done'assert agent.state.plan[1].status == 'done'assert agent.state.plan[2].status == 'current'- assert agent.state.current_plan_step_index == 2+ assert agent.state.current_plan_item_index == 2# ---------------------------------------------------------------------------@@ -93,10 +93,10 @@ async def test_plan_step_advancement(browser_session, mock_llm):async def test_replanning_replaces_old_plan(browser_session, mock_llm):agent = _make_agent(browser_session, mock_llm)agent.state.plan = [- PlanStep(text='Old step 1', status='done'),- PlanStep(text='Old step 2', status='current'),+ PlanItem(text='Old step 1', status='done'),+ PlanItem(text='Old step 2', status='current'),]- agent.state.current_plan_step_index = 1+ agent.state.current_plan_item_index = 1agent.state.plan_generation_step = 1output = _make_agent_output(plan_update=['New step A', 'New step B', 'New step C'])@@ -105,7 +105,7 @@ async def test_replanning_replaces_old_plan(browser_session, mock_llm):assert len(agent.state.plan) == 3assert agent.state.plan[0].text == 'New step A'assert agent.state.plan[0].status == 'current'- assert agent.state.current_plan_step_index == 0+ assert agent.state.current_plan_item_index == 0# ---------------------------------------------------------------------------@@ -116,10 +116,10 @@ async def test_replanning_replaces_old_plan(browser_session, mock_llm):async def test_render_plan_description(browser_session, mock_llm):agent = _make_agent(browser_session, mock_llm)agent.state.plan = [- PlanStep(text='Navigate to search page', status='done'),- PlanStep(text='Search for "laptop"', status='current'),- PlanStep(text='Extract price from results', status='pending'),- PlanStep(text='Skipped step', status='skipped'),+ PlanItem(text='Navigate to search page', status='done'),+ PlanItem(text='Search for "laptop"', status='current'),+ PlanItem(text='Extract price from results', status='pending'),+ PlanItem(text='Skipped step', status='skipped'),]result = agent._render_plan_description()@@ -138,7 +138,7 @@ async def test_render_plan_description(browser_session, mock_llm):async def test_planning_disabled_returns_none(browser_session, mock_llm):agent = _make_agent(browser_session, mock_llm, enable_planning=False)- agent.state.plan = [PlanStep(text='Should not render')]+ agent.state.plan = [PlanItem(text='Should not render')]assert agent._render_plan_description() is None@@ -156,7 +156,7 @@ async def test_planning_disabled_returns_none(browser_session, mock_llm):async def test_replan_nudge_injected_at_threshold(browser_session, mock_llm):agent = _make_agent(browser_session, mock_llm, planning_replan_on_stall=3)- agent.state.plan = [PlanStep(text='Step 1', status='current')]+ agent.state.plan = [PlanItem(text='Step 1', status='current')]agent.state.consecutive_failures = 3# Track context messages@@ -176,7 +176,7 @@ async def test_replan_nudge_injected_at_threshold(browser_session, mock_llm):async def test_no_replan_nudge_below_threshold(browser_session, mock_llm):agent = _make_agent(browser_session, mock_llm, planning_replan_on_stall=3)- agent.state.plan = [PlanStep(text='Step 1', status='current')]+ agent.state.plan = [PlanItem(text='Step 1', status='current')]agent.state.consecutive_failures = 2initial_count = len(agent._message_manager.state.history.context_messages)@@ -197,7 +197,7 @@ async def test_flash_mode_schema_excludes_plan_fields():FlashOutput = AgentOutput.type_with_custom_actions_flash_mode(ActionModel)schema = FlashOutput.model_json_schema()- assert 'current_plan_step' not in schema['properties']+ assert 'current_plan_item' not in schema['properties']assert 'plan_update' not in schema['properties']assert 'thinking' not in schema['properties']@@ -213,42 +213,42 @@ async def test_full_mode_schema_includes_plan_fields_optional():FullOutput = AgentOutput.type_with_custom_actions(ActionModel)schema = FullOutput.model_json_schema()- assert 'current_plan_step' in schema['properties']+ assert 'current_plan_item' in schema['properties']assert 'plan_update' in schema['properties']# They should NOT be in required- assert 'current_plan_step' not in schema.get('required', [])+ assert 'current_plan_item' not in schema.get('required', [])assert 'plan_update' not in schema.get('required', [])# ----------------------------------------------------------------------------# 10. Out-of-bounds current_plan_step handled gracefully+# 10. Out-of-bounds current_plan_item handled gracefully# ---------------------------------------------------------------------------async def test_out_of_bounds_plan_step_clamped(browser_session, mock_llm):agent = _make_agent(browser_session, mock_llm)agent.state.plan = [- PlanStep(text='Step A', status='current'),- PlanStep(text='Step B'),+ PlanItem(text='Step A', status='current'),+ PlanItem(text='Step B'),]- agent.state.current_plan_step_index = 0+ agent.state.current_plan_item_index = 0# Way out of bounds high- output = _make_agent_output(current_plan_step=999)+ output = _make_agent_output(current_plan_item=999)agent._update_plan_from_model_output(output)- assert agent.state.current_plan_step_index == 1 # clamped to last valid index+ assert agent.state.current_plan_item_index == 1 # clamped to last valid indexassert agent.state.plan[0].status == 'done'assert agent.state.plan[1].status == 'current'# Negative indexagent.state.plan = [- PlanStep(text='Step X', status='current'),- PlanStep(text='Step Y'),+ PlanItem(text='Step X', status='current'),+ PlanItem(text='Step Y'),]- agent.state.current_plan_step_index = 1- output2 = _make_agent_output(current_plan_step=-5)+ agent.state.current_plan_item_index = 1+ output2 = _make_agent_output(current_plan_item=-5)agent._update_plan_from_model_output(output2)- assert agent.state.current_plan_step_index == 0 # clamped to 0+ assert agent.state.current_plan_item_index == 0 # clamped to 0assert agent.state.plan[0].status == 'current'@@ -270,7 +270,7 @@ async def test_no_plan_render_returns_none(browser_session, mock_llm):async def test_replan_nudge_disabled_when_zero(browser_session, mock_llm):agent = _make_agent(browser_session, mock_llm, planning_replan_on_stall=0)- agent.state.plan = [PlanStep(text='Step 1', status='current')]+ agent.state.plan = [PlanItem(text='Step 1', status='current')]agent.state.consecutive_failures = 100 # high but doesn't matterinitial_count = len(agent._message_manager.state.history.context_messages)@@ -292,3 +292,86 @@ async def test_no_replan_nudge_without_plan(browser_session, mock_llm):agent._inject_replan_nudge()after_count = len(agent._message_manager.state.history.context_messages)assert after_count == initial_count+++# ---------------------------------------------------------------------------+# 14. Exploration nudge fires when no plan exists after N steps+# ---------------------------------------------------------------------------+++async def test_exploration_nudge_fires_after_limit(browser_session, mock_llm):+ agent = _make_agent(browser_session, mock_llm, planning_exploration_limit=3)+ agent.state.plan = None+ agent.state.n_steps = 3 # at the limit++ initial_count = len(agent._message_manager.state.history.context_messages)+ agent._inject_exploration_nudge()+ after_count = len(agent._message_manager.state.history.context_messages)++ assert after_count == initial_count + 1+ msg = agent._message_manager.state.history.context_messages[-1]+ assert isinstance(msg.content, str) and 'PLANNING NUDGE' in msg.content+++# ---------------------------------------------------------------------------+# 15. No exploration nudge when plan already exists+# ---------------------------------------------------------------------------+++async def test_no_exploration_nudge_when_plan_exists(browser_session, mock_llm):+ agent = _make_agent(browser_session, mock_llm, planning_exploration_limit=3)+ agent.state.plan = [PlanItem(text='Step 1', status='current')]+ agent.state.n_steps = 10 # well above limit++ initial_count = len(agent._message_manager.state.history.context_messages)+ agent._inject_exploration_nudge()+ after_count = len(agent._message_manager.state.history.context_messages)+ assert after_count == initial_count+++# ---------------------------------------------------------------------------+# 16. No exploration nudge below the limit+# ---------------------------------------------------------------------------+++async def test_no_exploration_nudge_below_limit(browser_session, mock_llm):+ agent = _make_agent(browser_session, mock_llm, planning_exploration_limit=5)+ agent.state.plan = None+ agent.state.n_steps = 4 # below the limit++ initial_count = len(agent._message_manager.state.history.context_messages)+ agent._inject_exploration_nudge()+ after_count = len(agent._message_manager.state.history.context_messages)+ assert after_count == initial_count+++# ---------------------------------------------------------------------------+# 17. Exploration nudge disabled when planning_exploration_limit=0+# ---------------------------------------------------------------------------+++async def test_exploration_nudge_disabled_when_zero(browser_session, mock_llm):+ agent = _make_agent(browser_session, mock_llm, planning_exploration_limit=0)+ agent.state.plan = None+ agent.state.n_steps = 100 # high but doesn't matter++ initial_count = len(agent._message_manager.state.history.context_messages)+ agent._inject_exploration_nudge()+ after_count = len(agent._message_manager.state.history.context_messages)+ assert after_count == initial_count+++# ---------------------------------------------------------------------------+# 18. Exploration nudge disabled when enable_planning=False+# ---------------------------------------------------------------------------+++async def test_exploration_nudge_disabled_when_planning_off(browser_session, mock_llm):+ agent = _make_agent(browser_session, mock_llm, enable_planning=False, planning_exploration_limit=3)+ agent.state.plan = None+ agent.state.n_steps = 10 # above limit++ initial_count = len(agent._message_manager.state.history.context_messages)+ agent._inject_exploration_nudge()+ after_count = len(agent._message_manager.state.history.context_messages)+ assert after_count == initial_count