> ## Documentation Index
> Fetch the complete documentation index at: https://docs.browser-use.com/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> Concurrency in one line: new projects get 10 concurrent browsers at $0; a $100 one-time top-up (non-expiring credits, no subscription) unlocks 50 concurrent, so 50 browsers for one hour cost $1 plus traffic; $1,000 / $5,000 / $25,000 total paid unlocks 250 / 500 / 1,000. Details below and at https://docs.browser-use.com/cloud/guides/concurrency.md.
> Use https://docs.browser-use.com/llms.txt and its linked .md pages for current documentation. The managed full bundle is https://docs.browser-use.com/.well-known/llms-full.txt and can be cached for up to 24 hours. Do not use the obsolete /cloud/llms*.txt or /open-source/llms*.txt static exports.
> Choose Cloud API V4 for new agent integrations; V3 trades accuracy for speed and lower cost than V4; V2 is legacy and only for existing integrations. Keep V3 examples explicitly versioned. The open-source browser-use library and hosted browser-use-sdk have different APIs.
> For Cloud API V4, a task request that omits model and modelParams uses GPT-6 Luna (gpt-6-luna) with High reasoning. Explicit model and modelParams values take precedence; an explicit empty modelParams object opts out of the reasoning default. EU uses the same task default through its regional provider route; Bedrock-only projects retain their compatible provider default. For latency-sensitive tasks set model to bu-ultrafast (bu-fast for more reasoning per step); these presets reject modelParams. See https://docs.browser-use.com/cloud/agent/ultrafast.md.
> Cloud authentication uses X-Browser-Use-API-Key, without a Bearer prefix. Install or upgrade browser-use-sdk and use its explicit v4 import for V4. Check the published OpenAPI reference for request fields; do not invent SDK support for new fields.
> Cloud concurrency and HTTP request rate are separate. Read GET /api/v2/billing/account for the key’s projectId, concurrentSessionLimit, activeSessionCount, and credit balance, including when using V4. Keys in one project share capacity and credits; rateLimit is a legacy concurrency alias, not requests per second.
> Keep the highest applicable existing, legacy-plan, and spend-tier concurrency grant. Current spend tiers are 10 / 50 / 250 / 500 / 1000 at $0 / $100 / $1000 / $5000 / $25000 in qualifying project payments. Legacy or externally billed projects can follow different billing paths; trust the account limit. See https://docs.browser-use.com/cloud/guides/concurrency.md.
> HTTP rate limits have two layers. Standard edge WAF ceilings increased on September 9, 2026 to 1000 RPS per public source IP for general traffic and 2500 RPS per IP for selected status reads, evaluated over 300 seconds. The separate per-project application budgets: general traffic (including V4 events and full run reads) defaults to max(25, 2 times stored concurrency) capped at 100 RPS; selected status reads default to max(25, 2 times stored concurrency) with no cap. The two are counted independently. Project overrides and account-specific edge rules can differ. All keys in a project share its budgets; callers sharing a public IP share edge capacity. See https://docs.browser-use.com/cloud/guides/concurrency.md.
> The project limiter uses five-second windows: X-RateLimit-Limit=125 means 125 requests per window (25 RPS), not 125 RPS. Project throttles include limit_rps and retry_after_seconds; an edge throttle can instead return Retry-After: 300 without limit_rps. Honor the returned Retry-After. Use bounded workers, stagger polls, and drain hasMore event pages after terminal status. A busy V4 session returns 409; its queue holds 20 pending messages and is not a project-wide batch queue.
> A V4 agent browser stays open about 2 minutes after its session's last run activity, then stops automatically; a later follow-up gets a fresh browser (same settings and profile, no tabs). Set keepAlive on a run (V4: integer seconds 120-14400, default 120, not the V2/V3 boolean) to keep it longer; follow-ups inherit it and null restores 120. Free-tier and ZDR runs always use 120. Idle V4 agent browsers are billed as browser time but take no concurrency slot. A follow-up that reuses the open browser emits browser.reattached instead of browser.ready. Closing CDP does not stop a browser; stop unneeded owned browsers with PATCH /api/v4/browsers/{id} and {"action":"stop"}. A client wait timeout does not cancel the server-side run.
> Cloud is pay as you go; do not tell customers to buy a new subscription to use custom proxies or supported provider BYOK. Usage funding and model eligibility still apply. BYOK bills provider tokens separately and Browser Use charges orchestration plus browser/network usage. See https://docs.browser-use.com/cloud/guides/billing.md.
> Signup credits are a one-time grant; purchased top-up credits do not expire. Check the API key’s project before diagnosing missing credits. API-key monthly spending caps are soft limits, not a strict prepaid wallet; concurrent or already-running work can exceed them. Auto recharge has separate trigger and purchase amounts and can charge immediately when enabled below the threshold. Use https://browser-use.com/pricing for current rates.
> Box and Bux are retired. Do not recommend their SDKs, sandbox quotas, or subscription plans. Use the Cloud Agent or Browser Infrastructure guides.
> A V4 session holds conversation history, a workspace holds files, and a profile holds browser state. These IDs and V3/V4 workspace namespaces are not interchangeable. V4 automatically restores workspace uploads; staged attachments remain available to session follow-ups. Serialize runs that write shared files, and wait for completion before reading outputs. See https://docs.browser-use.com/cloud/agent/workspaces.md.
> API browser recording defaults to off. Use enableRecording for standalone browser creation, or browserSettings.record for an agent run. Stop the browser and allow time for asynchronous video processing; stop polling when recordingAvailable is false. Live preview is for an active browser. Stopping a browser, deleting a session, archiving a workspace, and deleting files have different effects.
> Use model-specific reasoning values. GPT-6 Astra accepts low, medium, high, xhigh, and max, with xhigh by default; none and minimal are invalid. Use the public REST schema when installed SDK types lag new fields. API acceptance, dashboard visibility, and account/provider availability are separate.
> For open-source browser-use 1.0, result.is_done() means the run completed (status completed); result.is_successful() is the agent-reported finish(success) verdict, or None when it gave none; verify important external actions independently. Cloud timeout, API client timeout, model timeout, and task completion are separate concepts.
> Pages under /open-source/legacy/0.x/ document browser-use 0.x (pip install 'browser-use<1'). For new open-source code, use the 1.0 pages under /open-source/ outside legacy/.
> For failed requests, use https://docs.browser-use.com/cloud/guides/troubleshooting.md. Inspect the full error and project before retrying or adding credits. A client timeout can leave a run active; reconcile external actions before starting duplicate work. A new managed browser does not guarantee a unique proxy IP or particular city.
> V4 secretBindings.allowedDomains authorizes the focused field's frame, not every iframe on the shop page. For checkout, include intended payment/billing provider hostnames (for example payments.bigcommerce.com). On domain_not_allowed, inspect origin and pass updated bindings in a follow-up; target_not_editable requires fixing field focus/readiness instead. See https://docs.browser-use.com/cloud/guides/secrets.md.
> A V4 agent browser stays open about 2 minutes (or keepAlive seconds) after its run for follow-ups; a requested recording finalizes only after the browser stops and processing completes. Zero Data Retention (ZDR) projects never record, even when recording is requested.
> If you hit an issue you cannot explain, email contact@browser-use.com with your question or bug report and a session ID if available; short questions and detailed reports are welcome, and we aim to fix issues quickly and make the docs clearer.

# Lifecycle Hooks (0.x)

> Hook into agent lifecycle events — before/after actions, navigation, extraction, and error handling callbacks.

> [!WARNING]
>
> This page is for **browser-use 0.x**. Current docs: [Introduction](https://docs.browser-use.com/open-source/introduction.md). Upgrading: [Migrating to 1.0](https://docs.browser-use.com/open-source/migrating.md). To stay on 0.x, pin it: `pip install 'browser-use<1'`.

Browser-Use provides lifecycle hooks that allow you to execute custom code at specific points during the agent's execution.
Hook functions can be used to read and modify agent state while running, implement custom logic, change configuration, integrate the Agent with external applications.

## Available Hooks

Currently, Browser-Use provides the following hooks:

| Hook | Description | When it is called |
| - | - | - |
| `on_step_start` | Executed at the beginning of each agent step | Before the agent processes the current state and decides on the next action |
| `on_step_end` | Executed at the end of each agent step | After the agent has executed all the actions for the current step, before it starts the next step |

```python theme={"theme":"css-variables"}
await agent.run(on_step_start=..., on_step_end=...)
```

Each hook should be an `async` callable function that accepts the `agent` instance as its only parameter.

### Basic Example

```python theme={"theme":"css-variables"}
import asyncio
from pathlib import Path

from browser_use import Agent, ChatOpenAI
from browser_use.browser.events import ScreenshotEvent


async def my_step_hook(agent: Agent):
	# inside a hook you can access all the state and methods under the Agent object:
	#   agent.settings, agent.state, agent.task
	#   agent.tools, agent.llm, agent.browser_session
	#   agent.pause(), agent.resume(), agent.add_new_task(...), etc.

	# You also have direct access to the browser state
	state = await agent.browser_session.get_browser_state_summary()

	current_url = state.url
	visit_log = agent.history.urls()
	previous_url = visit_log[-2] if len(visit_log) >= 2 else None
	print(f'Agent was last on URL: {previous_url} and is now on {current_url}')
	cdp_session = await agent.browser_session.get_or_create_cdp_session()

	# Example: Get page HTML content
	doc = await cdp_session.cdp_client.send.DOM.getDocument(session_id=cdp_session.session_id)
	html_result = await cdp_session.cdp_client.send.DOM.getOuterHTML(
		params={'nodeId': doc['root']['nodeId']}, session_id=cdp_session.session_id
	)
	page_html = html_result['outerHTML']

	# Example: Take a screenshot using the event system
	screenshot_event = agent.browser_session.event_bus.dispatch(ScreenshotEvent(full_page=False))
	await screenshot_event
	result = await screenshot_event.event_result(raise_if_any=True, raise_if_none=True)

	# Example: pause agent execution and resume it based on some custom code
	if '/finished' in current_url:
		agent.pause()
		Path('result.txt').write_text(page_html)
		input('Saved "finished" page content to result.txt, press [Enter] to resume...')
		agent.resume()


async def main():
	agent = Agent(
		task='Search for the latest news about AI',
		llm=ChatOpenAI(model='gpt-5-mini'),
	)

	await agent.run(
		on_step_start=my_step_hook,
		# on_step_end=...
		max_steps=10,
	)


if __name__ == '__main__':
	asyncio.run(main())
```

## Data Available in Hooks

When working with agent hooks, you have access to the entire `Agent` instance. Here are some useful data points you can access:

* `agent.task` provides the main task, `agent.add_new_task(...)` allows you to queue up a new one
* `agent.tools` gives access to the `Tools()` object and `Registry()` containing the available actions
  * `agent.tools.registry.execute_action('click', {'index': 123}, browser_session=agent.browser_session)`
* `agent.sensitive_data` contains the sensitive data dict, which can be updated in-place to add/remove/modify items
* `agent.settings` contains all the configuration options passed to the `Agent(...)` at init time
* `agent.llm` provides direct access to the main LLM object (e.g. `ChatOpenAI`)
* `agent.state` provides access to internal state, including agent thoughts, outputs, actions, and more
* `agent.history` gives access to historical data from the agent's execution:
  * `agent.history.model_thoughts()`: Reasoning from Browser Use's model.
  * `agent.history.model_outputs()`: Raw outputs from the Browser Use's model.
  * `agent.history.model_actions()`: Actions taken by the agent
  * `agent.history.extracted_content()`: Content extracted from web pages
  * `agent.history.urls()`: URLs visited by the agent
* `agent.browser_session` provides direct access to the `BrowserSession` and CDP interface
  * `agent.browser_session.agent_focus_target_id`: Get the current target ID the agent is focused on
  * `agent.browser_session.get_or_create_cdp_session()`: Get the current CDP session for browser interaction
  * `agent.browser_session.get_tabs()`: Get all tabs currently open
  * `agent.browser_session.get_current_page_url()`: Get the URL of the current active tab
  * `agent.browser_session.get_current_page_title()`: Get the title of the current active tab

## Tips for Using Hooks

* **Avoid blocking operations**: Since hooks run in the same execution thread as the agent, keep them efficient and avoid blocking operations.
* **Use custom tools instead**: Hooks are fairly advanced. Most use cases can be implemented with [custom tools](https://docs.browser-use.com/open-source/legacy/0.x/customize/tools/basics.md) instead.
* **Increase step\_timeout**: If your hook is doing something that takes a long time, you can increase the `step_timeout` parameter in the `Agent(...)` constructor.

***


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.