Skip to main content

Overview

The Stagehand class is the main entry point for Stagehand v3. It manages browser lifecycle, provides AI-powered automation methods, and handles both local and remote browser environments.
import { Stagehand } from "@browserbasehq/stagehand";

const stagehand = new Stagehand(options);
await stagehand.init();

Constructor

new Stagehand()

Create a new Stagehand instance.
const stagehand = new Stagehand(options: V3Options);
V3Options Interface:
interface V3Options {
  env: "LOCAL" | "BROWSERBASE";

  // Browserbase options (required when env = "BROWSERBASE")
  apiKey?: string;
  projectId?: string;
  browserbaseSessionID?: string;
  browserbaseSessionCreateParams?: Browserbase.Sessions.SessionCreateParams;

  // Local browser options
  localBrowserLaunchOptions?: LocalBrowserLaunchOptions;

  // AI/LLM configuration
  model?: ModelConfiguration;
  llmClient?: LLMClient;
  systemPrompt?: string;

  // Behavior options
  selfHeal?: boolean;
  experimental?: boolean;
  domSettleTimeout?: number;
  cacheDir?: string;

  // Logging options
  verbose?: 0 | 1 | 2;
  logInferenceToFile?: boolean;
  disablePino?: boolean;
  logger?: (line: LogLine) => void;
}

Configuration Parameters

env
"LOCAL" | "BROWSERBASE"
required
Environment to run the browser in.
  • "LOCAL" - Run browser locally using Chrome/Chromium
  • "BROWSERBASE" - Run browser on Browserbase cloud platform

Browserbase Options

apiKey
string
Browserbase API key. Required when env is "BROWSERBASE".Can also be set via BROWSERBASE_API_KEY environment variable.
projectId
string
Browserbase project ID. Required when env is "BROWSERBASE".Can also be set via BROWSERBASE_PROJECT_ID environment variable.
browserbaseSessionID
string
Resume an existing Browserbase session by ID instead of creating a new one.
browserbaseSessionCreateParams
object
Additional parameters for Browserbase session creation. See Browserbase documentation for details.

Local Browser Options

localBrowserLaunchOptions
LocalBrowserLaunchOptions
Configuration for local Chrome/Chromium browser.

AI/LLM Configuration

model
ModelConfiguration
Configure the AI model to use for automation. Can be either:
  • A string in the format "provider/model" (e.g., "openai/gpt-4o", "anthropic/claude-3-5-sonnet-20241022")
  • An object with detailed configuration
llmClient
LLMClient
Provide a custom LLM client implementation instead of using the default.
systemPrompt
string
Custom system prompt to guide AI behavior across all operations.

Behavior Options

selfHeal
boolean
Enable self-healing mode where actions can recover from failures.Default: true
experimental
boolean
Enable experimental features (may change between versions).Default: false
Use with caution in production. Experimental features may break or change between versions without notice.
domSettleTimeout
number
Default timeout for waiting for DOM to stabilize (in milliseconds).Default: 30000
cacheDir
string
Directory path for caching action observations to improve performance.

Logging Options

verbose
0 | 1 | 2
Logging verbosity level.
  • 0 - Minimal logging
  • 1 - Standard logging (default)
  • 2 - Detailed debug logging
Default: 1
logInferenceToFile
boolean
Log AI inference details to files for debugging.Default: false
disablePino
boolean
Disable the Pino logging backend (useful for custom logging integrations).Default: false
logger
(line: LogLine) => void
Custom logger function to receive log events.

Methods

init()

Initialize the Stagehand instance and launch the browser.
await stagehand.init(): Promise<void>
Must be called before using any other methods.

close()

Close the browser and clean up resources.
await stagehand.close(options?: { force?: boolean }): Promise<void>
force
boolean
Force close even if already closing.Default: false

agent()

Create an AI agent instance for autonomous multi-step workflows.
stagehand.agent(config?: AgentConfig): AgentInstance
See the agent() reference for detailed documentation.

Properties

page

Access pages for browser automation. Pages are accessed through the context.
// Get the first page (created automatically on init)
const page = stagehand.context.pages()[0];

// Or get the active page
const activePage = stagehand.context.activePage();

// Create a new page
const newPage = await stagehand.context.newPage();
Type: Page The page object provides methods for:
  • Navigation (goto(), reload(), goBack(), goForward())
  • Interaction (click(), type(), keyPress(), locator(), deepLocator())
  • Inspection (url(), title(), screenshot())
  • JavaScript evaluation (evaluate())
Important: AI-powered methods (act(), extract(), observe()) are called on the stagehand instance, not on the page object.

context

Access the browser context for managing multiple pages.
const context = stagehand.context;
Type: V3Context The context object provides:
  • newPage() - Create a new page/tab
  • pages() - Get all open pages
  • setActivePage(page) - Switch active page

metrics

Get usage metrics for AI operations.
const metrics = await stagehand.metrics;
Returns: Promise<V3Metrics> V3Metrics Interface:
interface V3Metrics {
  // Act metrics
  actPromptTokens: number;
  actCompletionTokens: number;
  actInferenceTimeMs: number;

  // Extract metrics
  extractPromptTokens: number;
  extractCompletionTokens: number;
  extractInferenceTimeMs: number;

  // Observe metrics
  observePromptTokens: number;
  observeCompletionTokens: number;
  observeInferenceTimeMs: number;

  // Agent metrics
  agentPromptTokens: number;
  agentCompletionTokens: number;
  agentInferenceTimeMs: number;

  // Totals
  totalPromptTokens: number;
  totalCompletionTokens: number;
  totalInferenceTimeMs: number;
}

history

Get the history of all operations performed.
const history = await stagehand.history;
Returns: Promise<ReadonlyArray<HistoryEntry>> HistoryEntry Interface:
interface HistoryEntry {
  method: "act" | "extract" | "observe" | "navigate";
  parameters: unknown;
  result: unknown;
  timestamp: string;
}

Code Examples

  • Browserbase
  • Local
  • Custom Model Config
  • Multi-Page
  • With Metrics
  • With Custom Logger
import { Stagehand } from "@browserbasehq/stagehand";

// Remote browser on Browserbase
const stagehand = new Stagehand({
  env: "BROWSERBASE",
  apiKey: process.env.BROWSERBASE_API_KEY,
  projectId: process.env.BROWSERBASE_PROJECT_ID,
  model: "anthropic/claude-3-5-sonnet-20241022"
});

await stagehand.init();
const page = stagehand.context.pages()[0];

await page.goto("https://example.com");
const data = await stagehand.extract("get page title", z.object({
  title: z.string()
}));

await stagehand.close();

Error Handling

Stagehand methods may throw the following errors:
  • StagehandInitError - Failed to initialize Stagehand
  • StagehandNotInitializedError - Methods called before init()
  • BrowserbaseSessionNotFoundError - Browserbase session not found
  • MissingLLMConfigurationError - No LLM API key or client configured
  • MissingEnvironmentVariableError - Required environment variable not set
  • StagehandEnvironmentError - Invalid environment configuration
Always handle errors appropriately:
try {
  const stagehand = new Stagehand({ env: "LOCAL" });
  await stagehand.init();
  // ... use stagehand
} catch (error) {
  console.error("Stagehand error:", error.message);
} finally {
  await stagehand?.close();
}

Best Practices

  1. Always call init() before using any other methods
  2. Always call close() when done to clean up resources
  3. Use try-finally to ensure cleanup even on errors
  4. Set appropriate timeouts based on your use case
  5. Enable selfHeal for more robust automation
  6. Use metrics to monitor token usage and costs
  7. Configure custom logger for production debugging
  8. Cache directory can significantly improve performance for repeated actions

Environment Variables

Stagehand recognizes the following environment variables:
  • BROWSERBASE_API_KEY - Browserbase API key
  • BROWSERBASE_PROJECT_ID - Browserbase project ID
  • OPENAI_API_KEY - OpenAI API key
  • ANTHROPIC_API_KEY - Anthropic API key
  • GOOGLE_API_KEY - Google AI API key
These can be overridden by passing values in the constructor options.