Skip to content

Using Stagehand v4: act, observe, extract and Replay Without Inference

Nov 18, 202610 min
TL;DRStagehand v4 is Browserbase's open-source browser SDK (MIT; TypeScript, Python, Go): use page.locator() for stable steps and call the model through act() and extract() only where judgment is needed; an Action returned by observe() can be replayed with no inference at all. Server-side caching works only on Browserbase browsers and must be enabled on request; Stagehand is Chromium-only, and v4 removed agent().

Look up & save

Loading dictionary…

中文版

Stagehand is an open-source browser automation SDK from Browserbase, the hosted-browser company. It is MIT-licensed and ships in TypeScript, Python and Go. Like Playwright, it lets you write code that opens pages and clicks buttons; unlike Playwright, it adds three methods that call a model: act() performs one action from a sentence, extract() turns page content into typed data, and observe() finds the actions available on a page.

On the five-layer map, Stagehand is a "hybrid SDK" in the AI layer: the control flow lives in your code, and only the steps you pick go to a model. Version 4, released in August 2026, changed a lot, so this post follows v4.

The question here: which steps are worth one model call, and how do you avoid paying for the same step again?

Who it is for

People who write TypeScript or Python and have a web flow that runs again and again (pull a report from an admin panel, fill in a fixed form, extract data from a page that keeps getting redesigned) and whose selectors keep breaking.

It is not a replacement for end-to-end tests. Stagehand states plainly that it is not a test framework: no expect(), no fixtures, no retries, no reports. Whether to move an existing Playwright suite is covered in Stagehand vs Playwright.

The three methods

act(): one action at a time. Give it an instruction such as act("click the sign in button"). Stagehand reads the page's accessibility tree (the page structure browsers prepare for screen readers, keeping elements such as buttons, inputs and links along with their names), asks the model to pick the target element and method, then performs it. The docs are blunt: putting several steps into one instruction is "unreliable"; split them into separate act() calls yourself.

extract(): typed data out. Give it an instruction plus a schema (Zod in TypeScript, Pydantic in Python, a type parameter in Go). Stagehand validates the result before returning it, so what you get is already typed. For links, declare the field as a URL type; Stagehand has the model pick an element ID and maps it back to the real URL on the page, so the URL itself is never generated by the model.

observe(): look before you touch. Give it a description such as observe("find the email input") and it returns candidate actions. Each Action carries a real selector, a method name and arguments. It only plans; it never touches the page.

observe() is the most overlooked of the three and the one that saves the most money. The next section explains why.

Which method for a given step

Which Stagehand method a step should use
Which Stagehand method a step should useWith a stable selector, use page.locator(); otherwise use extract() to read data, or observe() once and replay with act(Action) to click or fill, with selfHeal re-inferring once if the selector breaks. Stable selector? e.g. data-testid page.locator() no model, milliseconds Reading data? or clicking, filling extract() schema-validated observe() once returns Action + selector act(Action) replay, no inference Selector breaks selfHeal retries once Yes No Yes No fails

Based on the Stagehand v4 docs. page.locator() involves no model; act(Action) replay skips inference and the page snapshot.

Steps with a stable selector should not use a model. Stagehand v4 is a complete browser driver in its own right: page.goto(), page.locator().click() and fill() are all there. The official migration guide says the same thing: use page.locator() wherever a selector is stable, because a model call per step costs latency and money that a CSS selector does not.

To read data, use extract(). A table that would need a count() loop reading row by row becomes one extract() call with an array schema.

To click or fill, observe() first and replay. When act() receives an instruction, it runs inference every time. When it receives an Action returned by observe(), it executes the recorded selector directly; the docs say this "skips model inference, the page snapshot, and the DOM-settle wait." A form with ten fields becomes one observe("find all form input fields") call and ten act(field) replays: one inference for ten actions.

If a replayed selector stops resolving (the site was redesigned) and selfHeal is on, Stagehand re-infers the action once and retries. For a replayed Action, that is the real extent of "self-healing": one retry, and only if you turn it on. An instruction-style act("...") re-infers every time, so it keeps up with redesigns anyway, at the cost of inference on every run.

A complete example: log in and pull invoices

The example in the official README demonstrates all three methods. Cookies persist in a local folder, so the next run starts already signed in; as written, though, every run costs five inferences, so for a flow you run repeatedly, switch to the replay version in the next section:

import { localBrowser, Stagehand } from "@browserbasehq/stagehand";
import { z } from "zod/v4";

const browser = await localBrowser.launch({ userDataDir: "./browser-data" });
const stagehand = await Stagehand.create({
  browser,
  model: { modelName: "openai/gpt-5.4-mini", apiKey: process.env.OPENAI_API_KEY },
});

const [page] = await browser.context.pages();
await page.goto("https://app.example.com/login");

// observe() returns real selectors, so credentials never reach the model
const { data: email } = await stagehand.observe("find the email input");
const { data: password } = await stagehand.observe("find the password input");
await page.locator(email[0].selector).fill(process.env.APP_EMAIL!);
await page.locator(password[0].selector).fill(process.env.APP_PASSWORD!);

await stagehand.act("click the sign in button");
await stagehand.act("open the billing page");

const { data } = await stagehand.extract(
  "extract every invoice in the table",
  z.object({
    invoices: z.array(z.object({ number: z.string(), amount: z.number(), paid: z.boolean() })),
  }),
);
console.log(data.invoices);

await stagehand.close();
await browser.close();

Look at how the login works: the model only finds the input fields, and the actual credentials go in through an ordinary fill(), never entering a prompt. The alternative is the variables option on act(): write "type %password% into the password field", and Stagehand gives the model only the variable name, substituting the real value locally.

Not paying for the same step twice

Replay across runs. The docs show keeping observe() results in an in-memory Map for reuse within one run. To keep tomorrow's run free of inference too, save the Action to a file. In TypeScript an Action is a plain object (description, method, arguments, selector), so it serializes straight to JSON:

import { existsSync } from "node:fs";
import { readFile, writeFile } from "node:fs/promises";

// same setup as above, plus selfHeal
const stagehand = await Stagehand.create({ browser, selfHeal: true });

// First run: one inference, then save the Action
if (!existsSync("signin.json")) {
  const { data } = await stagehand.observe("find the sign in button");
  await writeFile("signin.json", JSON.stringify(data[0]));
}

// Every later run: read and replay, no model; selfHeal re-infers once if the selector breaks
const signIn = JSON.parse(await readFile("signin.json", "utf8"));
await stagehand.act(signIn);

Saving to a file extends the docs' in-memory version, so run it once before relying on it to confirm the object you read back replays. If selfHeal cannot rescue it, delete the file and observe() again.

Something you can do tonight: open the scraper that breaks most often, find the step that changes most often, and replace its hardcoded selector with observe(). Print the returned Action and see which element it picked. If it is right, save and replay it as above; if not, make the instruction more specific ("the search button in the header") and try again.

Stagehand has two mechanisms for skipping inference, and they apply in different places:

observe() plus replayBrowserbase server-side cache
HowKeep the Action yourself and pass it to act() laterOn by default once enabled; Stagehand.create({ cache }) turns it off or tunes the threshold
Where it worksLocal or BrowserbaseBrowserbase browsers only
Needs enablingNoEmail Browserbase to enable it for your project
Coversact()act(), observe(), extract()

The server-side cache key is built from the instruction text, the page content and the call options. It deliberately leaves out the model configuration, so switching models does not invalidate it. An identical call has to return the same result a threshold number of times (threshold) before the cache starts serving it; every result's metadata.cache.status tells you HIT, MISS or DISABLED.

Cases where caching fails or does not apply:

  • Local browsers have no cache at all. v4 has no client-side cache; the cache option does nothing on a local browser, and every call runs inference.
  • URLs with dynamic parameters may not match the cache.
  • Calls scoped with locator bypass the cache and report DISABLED.
  • Turn the cache off for calls that carry passwords. variables are normally never sent to the model, but with server-side caching enabled, their values travel to the cache service with the request. The docs recommend cache: false on calls with credentials.

What changed in v4

State management moved into the browser. Stagehand stopped being built on Playwright back in v3 and drives Chromium over CDP itself. v4 goes further and moves target management, frame tracking and CDP dispatch into an extension that starts with the browser. Your SDK talks to the extension over the existing CDP connection. A single click expands into several CDP commands, and those now all run inside the browser instead of each crossing the network.

Stagehand v3 vs v4: where CDP commands run
Stagehand v3 vs v4: where CDP commands runIn v3 the SDK keeps a copy of browser state locally and every CDP command crosses the network; in v4 the SDK sends one message to the Stagehand extension inside the browser, which issues the CDP commands to the page from there. v3 v4 BROWSER Your code (SDK) keeps a copy of state Browser Your code (SDK) sends requests only Stagehand extension Page each CDP command crosses the network one message CDP

Based on the Browserbase v4 launch post. With a remote browser, the network hop is where the latency comes from; with a local browser the difference is small.

The v4 launch post gives the reasoning: every framework that hands you a page object keeps a local copy of the browser's state, and when the browser is remote, the gap between copy and reality grows, which surfaces as errors like "Target page, context or browser has been closed." The gain is mostly for remote browsers; the post itself says there is less to gain when the browser is on your laptop. It includes one 50-action measurement against a remote browser using the experimental batch commands, compared with Playwright: the median goBack dropped from 139.5 ms to 17.5 ms. The authors note it is a single run, not a benchmark.

Domain policy moved into the browser too. Once you set browser.context.setDomainPolicy({ allowedDomains, blockedDomains }), even a pop-up the page opens with window.open is blocked before its request leaves; in v3 the window had to open first and then be closed.

The new architecture also lets the three languages share one core: each SDK becomes a thin client, which is how TypeScript, Python and Go shipped together with the same features.

agent() is gone. v3 had an agent() that wrapped act, extract and observe in a loop and had the model pick one tool per step. The v4 migration guide says it was built for "models that couldn't reliably drive a browser on their own" and now recommends two paths: have a coding agent write a Stagehand script and run that script (the recommended starting point), or hand the full Stagehand API to your own agent as tools. A later post in the series looks at why so many tools are dropping their built-in agent loops.

Limits

  • Chromium only. No Firefox or WebKit, and no automatic browser download; local runs use the Chrome you already have.
  • No auto-waiting. Stagehand resolves a selector once and throws if it is not there; goto() waits only for domcontentloaded by default. Wait explicitly with waitForSelector() before acting. What to watch for when porting from Playwright is covered in Stagehand vs Playwright.
  • Do not wrap act() in a retry loop. A failed act() may already have clicked or submitted. The migration guide and the cost page recommend retrying observe() (which only plans) and handing the result to act() exactly once; if you escalate to a stronger model, do it on observe(), not on act().
  • The API moves fast. From v2 to v4 took under a year and a half, and construction, return shapes and agent() all changed along the way, while model training data mostly holds the old patterns. That is why the project ships rule files for coding agents, meant for CLAUDE.md or .cursorrules.
  • Cloudflare Browser Run supports only v2.5.x. Cloudflare's explanation is that Stagehand v3 and later are not Playwright-based. For hosted v4 browsers, Browserbase is the main option today.
  • The accessibility tree is not magic. A May 2026 write-up, from before v4, on EHR (electronic health record) integrations describes moving from Stagehand back to Playwright: on complex DOMs the accessibility tree did not map to the right elements, and the failures they actually hit were random pop-ups, slow rendering and business edge cases, not redesigns. Stagehand addresses selectors that break because a site changed; it does not help with other kinds of flakiness.

Getting started

  1. Install: pnpm add @browserbasehq/stagehand 'zod@~4.4.3' (Python: pip install stagehand). Local runs need Chrome installed.
  2. Get an API key for a model and set it in the model field of Stagehand.create().
  3. Start from the example above: get it running with page.locator() everywhere first, then follow "Something you can do tonight" to swap the one or two steps that break most often.

If all you want is a browser for Claude Code or Codex, you do not need the SDK: Stagehand also ships a browse CLI that needs no model key and no Browserbase account for local use. The series post on browse.sh covers its skills directory.

References