Introduction to Stagehand
Relevant source files
The following files were used as context for generating this wiki page:
Stagehand is a browser automation framework designed to control web browsers using a combination of natural language and traditional code. It bridges the gap between high-level, unpredictable AI agents and low-level, code-intensive frameworks like Playwright or Selenium. By allowing developers to choose between AI-driven commands for unfamiliar pages and precise code for known workflows, Stagehand aims to make web automation more flexible, maintainable, and reliable for production environments.
The framework is built around a few core primitives that handle browser interactions. Key features include the ability to preview AI-generated actions before execution, auto-caching of repeatable actions to save time and LLM tokens, and self-healing capabilities that re-engage AI when a website's structure changes and breaks a previously cached automation.
Sources: README.md:25-39, packages/core/README.md:25-39
Core Architecture
The central component of the framework is the Stagehand class. A developer instantiates this class to gain access to all automation capabilities. The instance manages the browser connection, state, history, and provides the primary methods for interaction.
Sources: claude.md:3-4
Stagehand Class Diagram
The following diagram illustrates the public interface of the Stagehand class, showing its main properties and methods.
Initialization and Configuration
To begin, a Stagehand instance is created and initialized. Configuration options are passed to the constructor to define the execution environment, verbosity, and the AI model to be used.
import { Stagehand } from "@browserbasehq/stagehand";
const stagehand = new Stagehand({
env: "LOCAL", // or "BROWSERBASE"
verbose: 2, // 0, 1, or 2
model: "openai/gpt-4.1-mini",
});
await stagehand.init();
Sources: claude.md:11-19
Key configuration options include:
| Option | Description | Possible Values | Source |
|---|---|---|---|
env | Specifies the execution environment. | "LOCAL", "BROWSERBASE" | claude.md:12 |
verbose | Sets the logging verbosity level. | 0, 1, 2 | claude.md:13 |
model | Defines the LLM to be used for AI tasks. | e.g., "openai/gpt-4.1-mini", "google/gemini-2.0-flash" | claude.md:14 |
cua | Enables the Computer Use Agent (CUA) mode for agents. | true, false | packages/core/examples/cua-example.ts:28 |
Key Primitives
Stagehand's functionality is exposed through four main primitives: act, extract, observe, and agent. These methods are called on the stagehand instance.
Sources: README.md:47-64, claude.md:4-7
act()
The act() method executes a single, specific action on the current browser page, such as clicking a button or typing into a field. It takes a natural language instruction as input.
// Use act() to execute individual actions
await stagehand.act("click on the stagehand repo");
Sources: README.md:50-51
extract()
The extract() method is used to pull structured data from a webpage. It takes a natural language instruction and a zod schema that defines the desired output structure. This allows for reliable data extraction into a typed object.
const { author, title } = await stagehand.extract(
"extract the author and title of the PR",
z.object({
author: z.string().describe("The username of the PR author"),
title: z.string().describe("The title of the PR"),
}),
);
Sources: README.md:58-67
observe()
The observe() method allows you to preview the actions an AI would take for a given instruction without actually executing them. It returns a list of candidate Action objects. This is useful for building more predictable workflows by first observing and then explicitly choosing which action to act on.
This "Observe-Act" pattern is the recommended approach for robust automation.
Sources: claude.md:57-65
agent()
For more complex, multi-step tasks, Stagehand provides an agent(). The agent can be given a high-level instruction and will autonomously perform a sequence of actions to achieve the goal.
// Use agent() for multi-step tasks
const agent = stagehand.agent();
await agent.execute("Get to the latest PR");
Sources: README.md:53-55
There are specialized agents, such as the Computer Use Agent (CUA), which is designed for more advanced scenarios and works with specific computer-use models.
Sources: packages/core/examples/cua-example.ts:27-38
Typical Automation Workflow
The following diagram shows a typical workflow using Stagehand's primitives.
Sources: README.md:47-67, claude.md:11-100
Stagehand Server API
In addition to the core TypeScript library, Stagehand can be run as a server, exposing its capabilities via a RESTful API. This allows integrations with other languages and systems. The server manages browser sessions and exposes endpoints for the core primitives.
Sources: packages/server/README.md:1-4, packages/server/openapi.v3.yaml
The API is defined in an OpenAPI v3 specification. Below are some of the key endpoints:
| Endpoint | Method | Description |
|---|---|---|
/v1/sessions/start | POST | Starts a new browser session. |
/v1/sessions/{id}/act | POST | Executes an action within a session. |
/v1/sessions/{id}/extract | POST | Extracts data from the page in a session. |
/v1/sessions/{id}/observe | POST | Observes possible actions in a session. |
/v1/sessions/{id}/navigate | POST | Navigates to a new URL. |
/v1/sessions/{id}/end | POST | Ends a browser session. |
Sources: packages/server/openapi.v3.yaml:7-133
Observability and Metrics
Stagehand provides a metrics property that offers insight into the performance and cost of AI operations. This includes token counts for prompts and completions, as well as inference times for each primitive.
The StagehandMetrics object contains the following fields:
| Metric | Type | Description |
|---|---|---|
actPromptTokens | number | Prompt tokens used by act. |
actCompletionTokens | number | Completion tokens used by act. |
actInferenceTimeMs | number | Inference duration for act. |
extractPromptTokens | number | Prompt tokens used by extract. |
extractCompletionTokens | number | Completion tokens used by extract. |
extractInferenceTimeMs | number | Inference duration for extract. |
observePromptTokens | number | Prompt tokens used by observe. |
observeCompletionTokens | number | Completion tokens used by observe. |
observeInferenceTimeMs | number | Inference duration for observe. |
agentPromptTokens | number | Prompt tokens used by agent. |
agentCompletionTokens | number | Completion tokens used by agent. |
agentInferenceTimeMs | number | Inference duration for agent. |
totalPromptTokens | number | Total prompt tokens used in the session. |
totalCompletionTokens | number | Total completion tokens used in the session. |
totalInferenceTimeMs | number | Total inference time for the session. |
Sources: packages/core/tests/public-api/v3-core.test.ts:60-87
Summary
Stagehand provides a powerful and flexible approach to browser automation by integrating AI with traditional coding practices. Its core primitives (act, extract, observe, agent) offer different levels of abstraction, from single, precise actions to autonomous, multi-step task execution. With features like a server-side API, detailed metrics, and self-healing capabilities, Stagehand is positioned as a robust framework for building and maintaining production-grade browser automations.