> ## 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
> 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; V2 is the lower-cost option for simple tasks. Keep V3 examples explicitly versioned. The open-source browser-use library and hosted browser-use-sdk have different APIs.
> 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 completed run or closed CDP connection does not immediately stop its cloud 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, is_done only reports a terminal done action. is_successful is the agent-reported outcome; verify important external actions independently. Cloud timeout, API client timeout, model timeout, and task completion are separate concepts.
> 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.

# Chat UI

> Full end-to-end example. Build a chat UI with live browser preview, follow-up tasks, recording, and streaming messages.

<Card title="Full source code" icon="github" href="https://github.com/browser-use/chat-ui-example">
  Clone and run in minutes. Next.js + Browser Use SDK v3.
</Card>

This tutorial walks through the [chat-ui-example](https://github.com/browser-use/chat-ui-example) — a Next.js app that lets users chat with a Browser Use agent in real time. We focus on the SDK integration, not the UI components.

The app has two pages:

1. **Home** — the user types a task, the app creates a session and sends the task.
2. **Session** — live browser preview, streaming messages, follow-ups, and recording download.

All SDK calls live in a single file: `src/lib/api.ts`.

## Setup

```typescript api.ts theme={null}
import { BrowserUse } from "browser-use-sdk/v3";

// Server-only — no NEXT_PUBLIC_ prefix, never exposed to the browser
const apiKey = process.env.BROWSER_USE_API_KEY ?? "";
export const client = new BrowserUse({ apiKey });
```

<Note>
  The API key uses `BROWSER_USE_API_KEY` (no `NEXT_PUBLIC_` prefix) so it stays server-side. All SDK calls go through [server actions](https://nextjs.org/docs/app/guides/forms) — never call the SDK directly from client components.
</Note>

***

## 1. Create a session

```typescript actions.ts theme={null}
"use server";
import { client } from "./api";

export async function createSession() {
  const session = await client.sessions.create({
    keepAlive: true,
    enableRecording: true,
  });
  return { id: session.id, liveUrl: session.liveUrl, status: session.status };
}
```

* **`keepAlive: true`** keeps the session open after each task so the user can send follow-ups (default is `false`).
* **`enableRecording: true`** produces an MP4 video of the browser session.
* **`liveUrl`** is returned immediately — no waiting or extra call needed.

The home page creates the session, navigates to the session page (passing `liveUrl` and the initial task via URL params), and the session page takes over from there:

```typescript page.tsx theme={null}
async function handleSend(message: string) {
  const session = await createSession();

  router.push(
    `/session/${session.id}?liveUrl=${encodeURIComponent(session.liveUrl)}&task=${encodeURIComponent(message)}`
  );
}
```

***

## 2. Stream messages with `for await`

Instead of polling `sessions.get()` and `sessions.messages()` separately, use `client.run()` — it streams messages and resolves when the task completes:

```typescript session-context.tsx theme={null}
const streamTask = useCallback(async (task: string) => {
  const run = client.run(task, { sessionId });

  for await (const msg of run) {
    setMessages((prev) => [...prev, msg]);
  }

  // Iterator done — task reached terminal state
  setSession(run.result);
}, [sessionId]);
```

The `for await` loop yields each message as it arrives. When the loop ends, `run.result` contains the final session state (status, output, etc.). No separate status polling needed.

Wire it up in a `useEffect` to auto-run the initial task from URL params:

```typescript session-context.tsx theme={null}
useEffect(() => {
  if (!initialTask) return;
  sendMessage(initialTask);
}, []);
```

***

## 3. Follow-up tasks

Follow-ups call the same `streamTask` function — the stream already includes the user message, so no optimistic insert is needed:

```typescript session-context.tsx theme={null}
const sendMessage = useCallback(async (task: string) => {
  await streamTask(task);
}, [streamTask]);
```

The SDK auto-sets `keepAlive: true` when targeting an existing session, so follow-up tasks work without extra config.

***

## 4. Recording

Fetch the MP4 URL after the session ends (recording was enabled in step 1):

```typescript session-context.tsx theme={null}
useEffect(() => {
  if (!isTerminal) return;

  client.sessions.waitForRecording(sessionId).then((urls) => {
    if (urls.length) setRecordingUrls(urls);
  });
}, [isTerminal, sessionId]);
```

`waitForRecording` polls for up to 15 seconds and returns presigned MP4 download URLs. Returns an empty array if the agent answered without opening a browser.

***

## 5. Stop a task

```typescript actions.ts theme={null}
export async function stopTask(id: string) {
  await client.sessions.stop(id, { strategy: "task" });
}
```

Using `strategy: "task"` stops only the current task, keeping the session alive for follow-ups.

***

## 6. Session page

The session page consumes everything through a context provider:

```typescript session/[id]/page.tsx theme={null}
function SessionPage() {
  const { session, turns, isBusy, isTerminal, recordingUrls, sendMessage, stopTask } =
    useSession();

  return (
    <div className="flex h-screen w-full overflow-hidden">
      {/* Chat column */}
      <div className="flex-1 flex flex-col min-w-0">
        <ChatMessages turns={turns} isBusy={isBusy} />
        <ChatInput
          onSend={sendMessage}
          onStop={stopTask}
          disabled={isTerminal}
        />
      </div>

      {/* Live browser view — liveUrl available from session creation */}
      <BrowserPanel liveUrl={session?.liveUrl} />
    </div>
  );
}
```

***

## Summary

| Method                               | Purpose                                          |
| ------------------------------------ | ------------------------------------------------ |
| `client.sessions.create()`           | Create a session (returns `liveUrl` immediately) |
| `client.run()`                       | Send a task and stream messages with `for await` |
| `client.sessions.stop()`             | Stop the current task                            |
| `client.sessions.waitForRecording()` | Get MP4 recording URLs                           |
