Overview
TheStagehand 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.
Constructor
new Stagehand()
Create a new Stagehand instance.Configuration Parameters
Environment to run the browser in.
"LOCAL"- Run browser locally using Chrome/Chromium"BROWSERBASE"- Run browser on Browserbase cloud platform
Browserbase Options
Browserbase API key. Required when
env is "BROWSERBASE".Can also be set via BROWSERBASE_API_KEY environment variable.Browserbase project ID. Required when
env is "BROWSERBASE".Can also be set via BROWSERBASE_PROJECT_ID environment variable.Resume an existing Browserbase session by ID instead of creating a new one.
Additional parameters for Browserbase session creation. See Browserbase documentation for details.
Local Browser Options
Configuration for local Chrome/Chromium browser.
AI/LLM Configuration
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-sonnet-4-6") - An object with detailed configuration
Provide a custom LLM client implementation instead of using the default.
Custom system prompt to guide AI behavior across all operations.
Behavior Options
Enable self-healing mode where actions can recover from failures.Default:
trueEnable experimental features (may change between versions).Default:
false
Default timeout for waiting for DOM to stabilize (in milliseconds).Default:
30000Directory path for caching action observations to improve performance.
Controls whether the browser remains running after
stagehand.close() is called or the parent process exits unexpectedly.true- Browser continues running independently. On Browserbase, the session stays active. Locally, the Chrome process is kept alive.false- Browser is terminated and resources are cleaned up on close or crash.
browserbaseSessionCreateParams.keepAlive.Default: falseEnable or disable server-side caching for Can be overridden per-call via the
act(), extract(), and observe() requests. When enabled, repeated calls with the same inputs return instantly without consuming LLM tokens.Only applies when
env is "BROWSERBASE". Has no effect in local environments.serverCache option on act(), extract(), and observe().Default: trueLogging Options
Logging verbosity level.
0- Minimal logging1- Standard logging (default)2- Detailed debug logging
1Log AI inference details to files for debugging.Default:
falseDisable the Pino logging backend (useful for custom logging integrations).Default:
falseCustom logger function to receive log events.
Methods
init()
Initialize the Stagehand instance and launch the browser.close()
Close the browser and clean up resources.Force close even if already closing.Default:
falseWhen
keepAlive is true, calling close() disconnects Stagehand from the browser without terminating it. The browser session continues running independently and can be reconnected to later using browserbaseSessionID. When keepAlive is false (the default), close() fully terminates the browser and cleans up all resources.agent()
Create an AI agent instance for autonomous multi-step workflows.Properties
page
Access pages for browser automation. Pages are accessed through the context.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())
context
Access the browser context for managing multiple pages.V3Context
The context object provides:
newPage()- Create a new page/tabpages()- Get all open pagessetActivePage(page)- Switch active page
metrics
Get usage metrics for AI operations.Promise<StagehandMetrics>
StagehandMetrics Interface:
history
Get the history of all operations performed.Promise<ReadonlyArray<HistoryEntry>>
HistoryEntry Interface:
browserbaseSessionID
Browserbase session identifier for the active Browserbase run.string | undefined — undefined for LOCAL runs or before init().
browserbaseSessionURL
Shareable link to the active Browserbase session dashboard.string | undefined — undefined until a Browserbase session is active.
browserbaseDebugURL
Debugger URL returned by Browserbase for direct CDP inspection.string | undefined — undefined for LOCAL runs or if Browserbase doesn’t provide one.
Code Examples
- Browserbase
- Local
- Custom Model Config
- Multi-Page
- With Metrics
- With Custom Logger
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
Best Practices
- Always call
init()before using any other methods - Always call
close()when done to clean up resources - Use try-finally to ensure cleanup even on errors
- Set appropriate timeouts based on your use case
- Enable
selfHealfor more robust automation - Use metrics to monitor token usage and costs
- Configure custom logger for production debugging
- Cache directory can significantly improve performance for repeated actions
Environment Variables
Stagehand recognizes the following environment variables:BROWSERBASE_API_KEY- Browserbase API keyBROWSERBASE_PROJECT_ID- Browserbase project IDOPENAI_API_KEY- OpenAI API keyANTHROPIC_API_KEY- Anthropic API keyGOOGLE_API_KEY- Google AI API key

