Skip to content

Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.

Update step handling in Agent class

Magnus Müller2d31052e3d0b
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.py
index 8c3f38edc..f5df5fab4 100644
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@ -640,9 +640,6 @@ class Agent(Generic[Context, AgentStructuredOutput]):
# Initialize timing first, before any exceptions can occur
self.step_start_time = time.time()
- # Increment step counter at the start of each step
- self.state.n_steps += 1
-
browser_state_summary = None
try:
@@ -669,7 +666,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):
assert self.browser_session is not None, 'BrowserSession is not set up'
- self.logger.debug(f'🌐 Step {self.state.n_steps}: Getting browser state...')
+ self.logger.debug(f'🌐 Step {self.state.n_steps + 1}: Getting browser state...')
browser_state_summary = await self._get_browser_state_with_recovery(cache_clickable_elements_hashes=True)
current_page = await self.browser_session.get_current_page()
@@ -677,7 +674,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):
await self._raise_if_stopped_or_paused()
# Update action models with page-specific actions
- self.logger.debug(f'📝 Step {self.state.n_steps}: Updating action models...')
+ self.logger.debug(f'📝 Step {self.state.n_steps + 1}: Updating action models...')
await self._update_action_models_for_page(current_page)
# Get page-specific filtered actions
@@ -688,7 +685,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):
page_action_message = f'For this page, these additional actions are available:\n{page_filtered_actions}'
self._message_manager._add_message_with_type(UserMessage(content=page_action_message), 'consistent')
- self.logger.debug(f'💬 Step {self.state.n_steps}: Adding state message to context...')
+ self.logger.debug(f'💬 Step {self.state.n_steps + 1}: Adding state message to context...')
self._message_manager.add_state_message(
browser_state_summary=browser_state_summary,
model_output=self.state.last_model_output,
@@ -707,7 +704,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):
"""Execute LLM interaction with retry logic and handle callbacks"""
input_messages = self._message_manager.get_messages()
self.logger.debug(
- f'🤖 Step {self.state.n_steps}: Calling LLM with {len(input_messages)} messages (model: {self.llm.model})...'
+ f'🤖 Step {self.state.n_steps + 1}: Calling LLM with {len(input_messages)} messages (model: {self.llm.model})...'
)
model_output = await self._get_model_output_with_retry(input_messages)
@@ -716,7 +713,8 @@ class Agent(Generic[Context, AgentStructuredOutput]):
# Check again for paused/stopped state after getting model output
await self._raise_if_stopped_or_paused()
- # NOTE: n_steps is now incremented at the start of step() method
+ # Increment step counter at the start of each step
+ self.state.n_steps += 1
# Handle callbacks and conversation saving
await self._handle_post_llm_processing(browser_state_summary, input_messages)
@@ -865,7 +863,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):
"""Get model output with retry logic for empty actions"""
model_output = await self.get_model_output(input_messages)
self.logger.debug(
- f'✅ Step {self.state.n_steps}: Got LLM response with {len(model_output.action) if model_output.action else 0} actions'
+ f'✅ Step {self.state.n_steps + 1}: Got LLM response with {len(model_output.action) if model_output.action else 0} actions'
)
if (
@@ -992,7 +990,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):
url_short = current_page.url[:50] + '...' if len(current_page.url) > 50 else current_page.url
interactive_count = len(browser_state_summary.selector_map) if browser_state_summary else 0
self.logger.info(
- f'📍 Step {self.state.n_steps}: Evaluating page with {interactive_count} interactive elements on: {url_short}'
+ f'📍 Step {self.state.n_steps + 1}: Evaluating page with {interactive_count} interactive elements on: {url_short}'
)
def _log_next_action_summary(self, parsed: 'AgentOutput') -> None:
diff --git a/browser_use/agent/views.py b/browser_use/agent/views.py
index 4398bdd5a..379dc7486 100644
--- a/browser_use/agent/views.py
+++ b/browser_use/agent/views.py
@@ -70,7 +70,7 @@ class AgentState(BaseModel):
"""Holds all state information for an Agent"""
agent_id: str = Field(default_factory=uuid7str)
- n_steps: int = 0
+ n_steps: int = 1
consecutive_failures: int = 0
last_result: list[ActionResult] | None = None
history: AgentHistoryList = Field(default_factory=lambda: AgentHistoryList(history=[], usage=None))