The Agent Lifecycle
Relevant source files
The following files were used as context for generating this wiki page:
The Agent Lifecycle in browser-use governs the iterative process by which an AI agent perceives the browser state, reasons about a given task, and executes actions to achieve a goal. The lifecycle is primarily managed by the Agent class, which orchestrates communication between the Large Language Model (LLM), the MessageManager, and the Controller to navigate and interact with web environments.
This lifecycle is designed to be robust, supporting features such as multi-step execution, planning intervals, error handling with retries, and manual control flags for pausing or stopping execution.
1. Initialization and Setup
Before an agent can begin its task, it undergoes a comprehensive initialization phase. This phase sets up the necessary browser environment, configures the message management system, and prepares the action registry.
Core Components during Initialization
- LLM Configuration: The agent is initialized with a primary LLM for reasoning and optional specialized LLMs for planning and page extraction.
- Browser Context: If not provided, the agent creates a new
BrowserandBrowserContextto isolate the session. - Message Manager: A
MessageManageris instantiated to handle the prompt construction, token counting, and historical context of the conversation. - Controller: The
Controlleris linked to provide the set of available actions that the agent can execute.
Sources: browser_use/agent/service.py:73-195, browser_use/agent/message_manager/service.py:33-100
Initial State and Action Processing
The agent can be configured with initial_actions which are executed immediately upon starting the run() loop. This is useful for pre-setting the browser state (e.g., logging in or navigating to a specific domain) before the LLM begins its autonomous reasoning.
Sources: browser_use/agent/service.py:465-475, browser_use/agent/service.py:1010-1030
2. The Execution Loop (run)
The primary entry point for the agent lifecycle is the run() method. It executes a loop for a maximum number of steps (defaulting to 100) or until a "done" action is triggered.
The diagram above shows the high-level control flow of the agent's main execution loop.
Sources: browser_use/agent/service.py:462-510, browser_use/agent/service.py:521-534
3. The Step Process
The step() method represents a single iteration of the perception-action cycle. It involves capturing the current browser state, optionally running a planner, generating an action sequence via the LLM, and executing those actions.
Step Components and Logic
- State Capture: The agent retrieves the current
BrowserStateincluding the DOM tree, open tabs, and a screenshot. - Planning (Optional): If a
planner_llmis configured and the interval is reached, the agent runs a planning prompt to evaluate progress. - Action Generation: The
get_next_actionmethod sends the formatted messages to the LLM. - Multi-Action Execution: The
Controller.multi_actmethod executes the sequence of actions provided by the LLM.
Sources: browser_use/agent/service.py:214-275, browser_use/controller/service.py:321-356
Message Management and Tokenization
The MessageManager maintains the conversation history. It ensures that the system prompt, task instructions, and browser state messages fit within the max_input_tokens limit. If the limit is exceeded, it uses cut_messages to proportionally remove content from the oldest state messages.
Sources: browser_use/agent/message_manager/service.py:175-225, browser_use/agent/message_manager/service.py:236-285
4. Reasoning and Planning
The agent supports specialized reasoning patterns to improve task success rates.
Planning Intervals
When planner_llm is set, the agent periodically analyzes the history to identify roadblocks and suggest next steps. This plan is injected into the message history to guide the primary LLM.
Sequence diagram showing the interaction between the primary LLM and the optional Planner LLM.
Sources: browser_use/agent/service.py:1032-1065, browser_use/agent/prompts.py:192-212
System Prompt Structure
The agent uses a structured SystemPrompt that enforces JSON output and defines rules for element interaction, navigation, and visual context.
| Section | Description |
|---|---|
| Response Format | Mandates valid JSON with current_state (summary, evaluation, memory, goal) and action list. |
| Action Sequencing | Allows up to max_actions_per_step (default 10) to be executed in order. |
| Element Interaction | Restricts interactions to valid numeric indexes from the DOM tree. |
| Visual Context | Instructs the agent to use screenshots and bounding boxes to verify layout. |
Sources: browser_use/agent/prompts.py:20-100
5. Action Execution and Results
The Controller is responsible for translating the LLM's requested actions into Playwright commands.
ActionResult and State History
Every action execution returns an ActionResult. These results are aggregated and stored in AgentHistory, which maps the model output to the actual browser state and results.
Sources: browser_use/agent/views.py:34-42, browser_use/agent/views.py:68-80
Error Handling and Failure Recovery
If a step fails (e.g., a timeout, rate limit, or validation error), the agent increments consecutive_failures. It will attempt to retry the step until max_failures is reached. Some errors, like "Max token limit reached," trigger proactive token cutting in the MessageManager.
Sources: browser_use/agent/service.py:288-312, browser_use/agent/views.py:246-258
6. Post-Run and Artifacts
Upon completion or failure, the agent performs cleanup and generates artifacts.
Telemetry and History
The lifecycle ends with the capture of AgentEndTelemetryEvent. The agent can save its execution history to a JSON file using AgentHistoryList.save_to_file().
Sources: browser_use/agent/service.py:511-525, browser_use/agent/views.py:133-143
Visualization (GIF Generation)
A unique feature of the lifecycle is the ability to generate a GIF of the entire task. The create_history_gif method stitches together screenshots from each step and overlays the agent's current goal and step number.
Sources: browser_use/agent/service.py:700-750, browser_use/agent/service.py:843-900
Summary of Configuration Options
| Parameter | Type | Default | Description |
|---|---|---|---|
max_failures | int | 3 | Number of consecutive errors allowed before stopping. |
planning_interval | int | 1 | Frequency (in steps) of running the planner LLM. |
use_vision | bool | True | Whether to include screenshots in the LLM prompts. |
max_actions_per_step | int | 10 | Max actions the LLM can request in one sequence. |
validate_output | bool | False | If true, runs a separate LLM call to validate the final result. |
Sources: browser_use/agent/service.py:73-125
The agent lifecycle is a closed-loop system that prioritizes accurate browser interaction through structured JSON responses, visual verification, and robust state management. By separating message management, browser control, and reasoning, the architecture allows for complex multi-step automations with built-in recovery mechanisms.