可靠性与人工介入

Attach your own CDP observer to a live V4 browser and save request metadata.

You can attach a CDP client to a live V4 browser and record its network events. This is a live observer, not a download of everything that happened during a run. V4 run events describe agent activity; they are not the browser's HTTP request log.

Find the live browser

For an agent run, watch its ordered run events for browser.ready or browser.reattached. The event's data.browser_session_id identifies the browser. You can also list the session's browsers with GET /api/v4/browsers?agentSessionId=SESSION_ID. A session can use more than one browser over time, so do not assume the first browser lasts for every follow-up.

Use an API key with browser read access in the same project to retrieve the active browser's cdpUrl. BROWSER_SESSION_ID is a browser ID, not a run ID or agent session ID.

export BROWSER_SESSION_ID="your-active-browser-id"
# BROWSER_USE_API_KEY must already be set. Do not print the resulting CDP URL.
set -o pipefail
BROWSER_CDP_URL="$(curl --fail --silent --show-error \
  "https://api.browser-use.com/api/v4/browsers/$BROWSER_SESSION_ID" \
  -H "X-Browser-Use-API-Key: $BROWSER_USE_API_KEY" \
  | jq --exit-status --raw-output '.cdpUrl // empty')" || exit 1
export BROWSER_CDP_URL

For a standalone V4 browser, you can use cdpUrl from the create response instead. A stopped browser has no live CDP URL. Check the HTTP status and browser state if discovery fails; do not create a replacement browser and mistake it for the agent's browser.

Treat the CDP URL as a credential. Anyone who can connect can control the browser and read its session. Keep it out of logs, tickets, source control, and shared shell history.

Record metadata from existing pages

Install Playwright with pip install playwright. No local browser download is needed because this example connects to an existing browser.

Save this as capture_network.py, then run python capture_network.py. It records for 30 seconds and creates network.jsonl with owner-only permissions. It refuses to overwrite an existing file. Start it before the activity you want to observe.

import asyncio
import json
import os
from urllib.parse import urlsplit

from playwright.async_api import async_playwright

def http_origin(value):
    try:
        url = urlsplit(value)
        if url.scheme not in {"http", "https"} or not url.hostname:
            return None
        host = f"[{url.hostname}]" if ":" in url.hostname else url.hostname
        port = url.port
    except ValueError:
        return None  # A malformed URL must not interrupt the capture.
    default_port = {"http": 80, "https": 443}[url.scheme]
    suffix = f":{port}" if port not in (None, default_port) else ""
    return f"{url.scheme}://{host}{suffix}"

async def main():
    async with async_playwright() as p:
        cdp_url = os.environ["BROWSER_CDP_URL"]
        try:
            browser = await p.chromium.connect_over_cdp(cdp_url)
        except Exception:
            # Transport errors can include the credential-bearing CDP URL.
            raise RuntimeError("Check the live CDP URL and browser state") from None
        context = browser.contexts[0]
        sessions = []
        fd = os.open("network.jsonl", os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)

        with os.fdopen(fd, "w") as output:
            def write(row):
                output.write(json.dumps(row) + "\n")
                output.flush()

            async def observe(page, page_number):
                cdp = await context.new_cdp_session(page)
                sessions.append(cdp)

                def record(event, params):
                    row = {"event": event, "page": page_number,
                           "requestId": params["requestId"]}
                    if event == "request":
                        request = params["request"]
                        row.update(method=request["method"],
                                   origin=http_origin(request["url"]),
                                   resourceType=params.get("type"))
                    elif event == "response":
                        response = params["response"]
                        row.update(status=response["status"],
                                   mimeType=response["mimeType"])
                    elif event == "finished":
                        row["bytes"] = params["encodedDataLength"]
                    else:
                        row["error"] = params.get("errorText")
                    write(row)

                events = {
                    "requestWillBeSent": "request", "responseReceived": "response",
                    "loadingFinished": "finished", "loadingFailed": "failed",
                }
                for name, event in events.items():
                    cdp.on(f"Network.{name}",
                           lambda params, event=event: record(event, params))
                await cdp.send("Network.enable")

            try:
                for number, page in enumerate(context.pages, start=1):
                    await observe(page, number)
                print(f"Observing {len(sessions)} existing page(s) for 30 seconds")
                await asyncio.sleep(30)
            finally:
                for cdp in sessions:
                    try:
                        await cdp.detach()
                    except Exception:
                        pass  # The page or browser may already have closed.

asyncio.run(main())

Each request is correlated by (page, requestId). A response row gives the HTTP status; a finished row gives transferred bytes. Keep the event sequence: redirects can produce more than one request event with the same request ID. Empty output means no matching events were observed, not that the run made no requests.

The example does not navigate, intercept requests, change the cache, or stop the browser. It drops URL paths, queries, credentials, headers, cookies, and request and response bodies. HTTP origins retain non-default ports; malformed and non-HTTP URLs have a null origin. Origins can still be sensitive; review the file before sharing it. Keep a bounded capture duration and a retention policy.

Coverage and lifecycle

  • Capture starts only after Network.enable for each attached page. Earlier traffic is not reconstructed, and attaching after browser.ready can miss startup requests.
  • This small example attaches only to pages present at startup. Popups, new tabs, workers, service workers, and some cross-process frames need separate target handling. It is not complete browser-wide capture.
  • Reattach if V4 provisions a new browser. A logger attached to the old browser cannot observe the replacement.
  • JSONL events are not HAR. A HAR exporter needs its own request, redirect, timing, and body handling. Network.getResponseBody is a separate, optional CDP call; bodies may be unavailable and can contain secrets or customer data.
  • Detaching an observer does not stop a browser or end its billing. Leave an agent-owned browser under the agent's lifecycle. For a standalone browser you created, stop it through the browser API when finished.

See the CDP Network reference and Playwright CDP sessions for event fields and target-specific behavior.


Configure residential or custom proxies for API V4 browsers and agent runs.

A US residential proxy is enabled by default. The browser's traffic passes through that residential IP before reaching the website, so the website sees the proxy's location—not your server's.

<img alt="A cloud browser routing its traffic through a residential proxy before reaching a website" />

<img alt="A cloud browser routing its traffic through a residential proxy before reaching a website" />

Set browser_settings / browserSettings when you create a V4 run to choose another country:

The current TypeScript SDK type requires proxyCountryCode whenever browserSettings is present. Use "us" to keep the default, or null to disable the managed proxy.

from browser_use_sdk.v4 import BrowserUse

client = BrowserUse()
run = client.runs.create(
    "Get the iPhone 16 price on amazon.de",
    browser_settings={"proxyCountryCode": "de"},
)
import { BrowserUse } from "browser-use-sdk/v4";

const client = new BrowserUse();
const run = await client.runs.create({
  task: "Get the iPhone 16 price on amazon.de",
  model: "grok-4.5",
  browserSettings: { proxyCountryCode: "de" },
});
curl https://api.browser-use.com/api/v4/runs \
  -H "X-Browser-Use-API-Key: $BROWSER_USE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"task":"Get the iPhone 16 price on amazon.de",
       "browserSettings":{"proxyCountryCode":"de"}}'

Disable proxies

Pass null for QA or internal sites that do not need a residential proxy:

run = client.runs.create(
    "Test my staging site",
    browser_settings={"proxyCountryCode": None},
)
const run = await client.runs.create({
  task: "Test my staging site",
  model: "grok-4.5",
  browserSettings: { proxyCountryCode: null },
});

Custom proxy

Custom proxies are available to all accounts, including free and pay-as-you-go accounts. No subscription is required. Normal credit, spend, and concurrency limits still apply.

The request format depends on what you are creating:

REST endpoint Custom proxy field
POST /api/v4/browsers Top-level customProxy
POST /api/v4/runs browserSettings.customProxy

browser_settings is the Python SDK keyword for agent runs. In REST JSON, the agent-run field is browserSettings.

Standalone browsers

For a browser you control with Playwright, Puppeteer, or another CDP client, put customProxy directly in the request body:

curl https://api.browser-use.com/api/v4/browsers \
  -H "X-Browser-Use-API-Key: $BROWSER_USE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "customProxy": {
      "host": "proxy.example.com",
      "port": 8080,
      "username": "YOUR_PROXY_USERNAME",
      "password": "YOUR_PROXY_PASSWORD"
    }
  }'

Replace the proxy details with yours. Omit both username and password if your proxy does not require authentication. Do not wrap these settings in browserSettings or browser_settings on /api/v4/browsers.

Keep the returned browser ID and stop the browser with PATCH /api/v4/browsers/{id} and {"action":"stop"} when finished. See the Create browser reference and Browser quickstart.

Agent runs

For a hosted agent, pass the proxy in the run's browser settings:

run = client.runs.create(
    "Check the account dashboard",
    browser_settings={
        "customProxy": {
            "host": "proxy.example.com",
            "port": 8080,
            "username": "user",
            "password": "pass",
            "ignoreCertErrors": False,
        }
    },
)
const run = await client.runs.create({
  task: "Check the account dashboard",
  model: "grok-4.5",
  browserSettings: {
    proxyCountryCode: "us",
    customProxy: {
      host: "proxy.example.com",
      port: 8080,
      username: "user",
      password: "pass",
      ignoreCertErrors: false,
    },
  },
});

A custom proxy overrides proxyCountryCode and must be passed again when a follow-up provisions a new browser. See the Create run reference for the complete settings object.


Trace agent execution steps and capture browser session recordings.

Overview

Browser Use has a native integration with Laminar - open-source platform for monitoring and analyzing error patterns in AI agents. Laminar SDK automatically captures agent execution steps, costs and browser session recordings of Browser Use agent. Browser session recordings allow developers to see full video replay of the browser session, which is useful for debugging Browser Use agent.

Setup

Install Laminar python SDK.

pip install lmnr

Register on Laminar Cloud or self-host Laminar, create a project and get the project API key from your project settings. Set the LMNR_PROJECT_API_KEY environment variable.

export LMNR_PROJECT_API_KEY=<your-project-api-key>

Usage

Initialize Laminar at the top of your project, and both Browser Use agent traces and session recordings will be automatically captured.

from browser_use import Agent, ChatGoogle
import asyncio

from lmnr import Laminar
import os

# At initialization time, Laminar auto-instruments
# Browser Use and any browser you use (local or remote)
Laminar.initialize(project_api_key=os.getenv('LMNR_PROJECT_API_KEY'))

async def main():
    agent = Agent(
        task="go to ycombinator.com, summarize 3 startups from the latest batch",
        llm=ChatGoogle(model="gemini-2.5-flash"),
    )
    await agent.run()

asyncio.run(main())

Viewing Traces

You can view traces in the Laminar UI by going to the traces tab in your project. When you select a trace, you can see both the browser session recording and the agent execution steps.

Timeline of the browser session is synced with the agent execution steps. In the trace view, you can also see the agent's current step, the tool it is using, and the tool's input and output.

<img alt="Laminar" />

Laminar

To learn more about how you can trace and evaluate your Browser Use agent with Laminar, check out Laminar docs.

Browser Use Cloud Authentication

Browser Use can sync your agent runs to the cloud for easy viewing and sharing. Authentication is required to protect your data.

Quick Setup

# Authenticate once to enable cloud sync for all future runs
browser-use auth
# Or if using module directly:
python -m browser_use.cli auth

Note: Cloud sync is enabled by default. If you have disabled it, you can re-enable with export BROWSER_USE_CLOUD_SYNC=true.

Manual Authentication

# Authenticate from code after task completion
from browser_use import Agent

agent = Agent(task="your task")
await agent.run()

# Later, authenticate for future runs
await agent.authenticate_cloud_sync()

Reset Authentication

# Force re-authentication with a different account
rm ~/.config/browseruse/cloud_auth.json
browser-use auth

Note: Authentication uses OAuth Device Flow - you must complete the auth process while the command is running. Links expire when the polling stops.


Write effective prompts for the agent. Tips for task descriptions, multi-step workflows, and getting reliable structured output.

Prompting can drastically improve performance and solve existing limitations of the library.

1. Be Specific vs Open-Ended

✅ Specific (Recommended)

task = """
1. Go to https://quotes.toscrape.com/
2. Use extract action with the query "first 3 quotes with their authors"
3. Save results to quotes.csv using write_file action
4. Do a google search for the first quote and find when it was written
"""

❌ Open-Ended

task = "Go to web and make money"

2. Name Actions Directly

When you know exactly what the agent should do, reference actions by name:

task = """
1. Use search action to find "Python tutorials"
2. Use click to open first result in a new tab
3. Use scroll action to scroll down 2 pages
4. Use extract to extract the names of the first 5 items
5. Wait for 2 seconds if the page is not loaded, refresh it and wait 10 sec
6. Use send_keys action with "Tab Tab ArrowDown Enter"
"""

See Available Tools for the complete list of actions.

3. Handle interaction problems via keyboard navigation

Sometimes buttons cannot be clicked (you may have found a bug in the library - open an issue). In many cases, you can work around this with keyboard navigation.

task = """
If the submit button cannot be clicked:
1. Use send_keys action with "Tab Tab Enter" to navigate and activate
2. Or use send_keys with "ArrowDown ArrowDown Enter" for form submission
"""

4. Custom Actions Integration

# When you have custom actions
@controller.action("Get 2FA code from authenticator app")
async def get_2fa_code():
    # Your implementation
    pass

task = """
Login with 2FA:
1. Enter username/password
2. When prompted for 2FA, use get_2fa_code action
3. NEVER try to extract 2FA codes from the page manually
4. ALWAYS use the get_2fa_code action for authentication codes
"""

5. Error Recovery

task = """
Robust data extraction:
1. Go to openai.com to find their CEO
2. If navigation fails due to anti-bot protection:
   - Use google search to find the CEO
3. If page times out, use go_back and try alternative approach
"""

The key to effective prompting is being specific about actions.


Poll ordered V4 events to monitor a run or build a custom UI.

If you only need the result, use runs.wait_for_completion() in Python or runs.waitForCompletion() in TypeScript. It polls the lightweight status endpoint instead of downloading every event.

For a custom UI, poll runs.events() with the previous cursor. Read status before fetching events so that the final fetch happens after you observe a terminal state, and drain all hasMore pages before stopping:

import time

after = None
while True:
    status = client.runs.status(run.id).status.value
    page = client.runs.events(run.id, after=after)
    for event in page.events:
        print(event.type, event.data)
    after = page.next_after if page.next_after is not None else after

    if status in {"completed", "failed", "cancelled"} and not page.has_more:
        break
    time.sleep(2)
let after: number | undefined;
while (true) {
  const { status } = await client.runs.status(run.id);
  const page = await client.runs.events(run.id, { after });
  for (const event of page.events) {
    console.log(event.type, event.data);
  }
  after = page.nextAfter ?? after;

  if (["completed", "failed", "cancelled"].includes(status) && !page.hasMore) break;
  await new Promise((resolve) => setTimeout(resolve, 2000));
}

Events cover run lifecycle, model calls, browser readiness, tool activity, artifacts, and completion. See Get run events for the complete response shape.

For browser HTTP request metadata, attach your own live CDP observer with Capture browser network events.

This two-second interval is an example for one stream, not a safe default for an unbounded batch. Event reads share the project's general request bucket. Use a shared rate limiter and stagger polling across runs. Keep the cursor when backing off after a 429, and resume from it rather than rereading history. See Concurrency and rate limits for capacity, request budgets, retries, and the separate per-session message queue.


Open the live browser, take over, then continue the same session.

Use a human checkpoint for approvals, authentication, payments, or review. After a run stops, get its live_view_url from the browser.ready event:

from browser_use_sdk.v4 import BrowserUse

client = BrowserUse()
run = client.runs.create(
    "Open the login page and stop for human review"
)
run = client.runs.wait_for_completion(run.id)

events = client.runs.events(run.id, limit=100)
ready = next(
    event for event in events.events
    if event.type == "browser.ready"
)
print(ready.data["live_view_url"])

# After the human finishes:
next_run = client.runs.create(
    "Continue from the current page",
    session_id=run.session_id,
)
import { BrowserUse } from "browser-use-sdk/v4";

const client = new BrowserUse();
const run = await client.runs.create({
  task: "Open the login page and stop for human review",
  model: "grok-4.5",
});
await client.runs.waitForCompletion(run.id);

const events = await client.runs.events(run.id, {
  limit: 100,
});
const ready = events.events.find(
  (event) => event.type === "browser.ready",
);
console.log(ready?.data.live_view_url);

// After the human finishes:
const nextRun = await client.runs.create({
  task: "Continue from the current page",
  model: "grok-4.5",
  sessionId: run.sessionId,
});

The same session preserves the conversation and workspace and reuses the live browser while it is available. Treat live-view URLs as credentials.


Sync a local login, then use it in an API V4 run.

Run the profile sync helper:

export BROWSER_USE_API_KEY=your_key
curl -fsSL https://browser-use.com/profile.sh | sh

Choose the accounts to sync, then use the returned profile ID:

from browser_use_sdk.v4 import BrowserUse

client = BrowserUse()
run = client.runs.create(
    "Check my LinkedIn messages",
    browser_settings={"profileId": "YOUR_PROFILE_ID"},
)
import { BrowserUse } from "browser-use-sdk/v4";

const client = new BrowserUse();
const run = await client.runs.create({
  task: "Check my LinkedIn messages",
  model: "grok-4.5",
  browserSettings: {
    profileId: "YOUR_PROFILE_ID",
    proxyCountryCode: "us",
  },
});

The profile supplies cookies and local storage without putting credentials in the prompt. Re-sync when the site's login expires.

A profile ID belongs to a project. Use an API key from that project, and do not substitute a workspace ID or conversation/session ID. Reusing a session may reuse its current browser; to apply a newly synced profile, create a fresh browser or conversation with that profile.

Cookie sync does not import a password manager or guarantee that the target site accepts a moved login. Sites can expire cookies, bind sessions to a device or network, or require another verification step. Use a stable proxy location when the site's security policy depends on location.