Stagehand constructor

// Basic usage
// Defaults to Browserbase; if no API key is provided, it will default to LOCAL
// Default model is gpt-4o
const stagehand = new Stagehand();

// Custom configuration
const stagehand = new Stagehand({
	env: "LOCAL",
	verbose: 1,
	enableCaching: true,
	logger: (logLine: LogLine) => {
		console.log(`[${logLine.category}] ${logLine.message}`);
	},
    localBrowserLaunchOptions: {
        headless: true, // Launches the browser in headless mode.
        executablePath: '/path/to/chrome', // Custom path to the Chrome executable.
        args: ['--no-sandbox', '--disable-setuid-sandbox'], // Additional launch arguments.
        env: { NODE_ENV: "production" }, // Environment variables for the browser process.
        handleSIGHUP: true,
        handleSIGINT: true,
        handleSIGTERM: true,
        ignoreDefaultArgs: false, // or specify an array of arguments to ignore.
        proxy: {
            server: 'http://proxy.example.com:8080',
            bypass: 'localhost',
            username: 'user',
            password: 'pass'
        },
        tracesDir: '/path/to/traces', // Directory to store trace files.
        userDataDir: '/path/to/user/data', // Custom user data directory.
        acceptDownloads: true,
        downloadsPath: '/path/to/downloads',
        extraHTTPHeaders: { 'User-Agent': 'Custom Agent' },
        geolocation: { latitude: 37.7749, longitude: -122.4194, accuracy: 10 },
        permissions: ["geolocation", "notifications"],
        locale: "en-US",
        viewport: { width: 1280, height: 720 },
        deviceScaleFactor: 1,
        hasTouch: false,
        ignoreHTTPSErrors: true,
        recordVideo: { dir: '/path/to/videos', size: { width: 1280, height: 720 } },
        recordHar: {
            path: '/path/to/har.har',
            mode: "full",
            omitContent: false,
            content: "embed",
            urlFilter: '.*'
        },
        chromiumSandbox: true,
        devtools: true,
        bypassCSP: false,
		cdpUrl: 'http://localhost:9222',
    },
});

// Resume existing Browserbase session
const stagehand = new Stagehand({
	env: "BROWSERBASE",
	browserbaseSessionID: "existing-session-id",
});

This constructor is used to create an instance of Stagehand.

Arguments: ConstructorParams

env
'LOCAL' | 'BROWSERBASE'

Defaults to 'BROWSERBASE'

apiKey
string

Your Browserbase API key. Defaults to BROWSERBASE_API_KEY environment variable

projectId
string

Your Browserbase project ID. Defaults to BROWSERBASE_PROJECT_ID environment variable

browserbaseSessionCreateParams
object

Configuration options for creating new Browserbase sessions. More information on browserbaseSessionCreateParams can be found here.

browserbaseSessionID
string

ID of an existing Browserbase session to resume

modelName
AvailableModel

Specifying the default language model to use

modelClientOptions
object

Configuration options for the language model client (i.e. apiKey)

enableCaching
boolean

Enables caching of LLM responses. When set to true, the LLM requests will be cached on disk and reused for identical requests. Defaults to false

domSettleTimeoutMs
integer

Specifies the timeout in milliseconds for waiting for the DOM to settle. Defaults to 30_000 (30 seconds)

logger
(message: LogLine) => void

message is a LogLine object. Handles log messages. Useful for custom logging implementations. For more information, see the Logging page

disablePino
boolean

Whether Pino should be disabled for logging. This is helpful for Next.js or test environments. Pino will automatically be disabled if a custom logger is defined.

verbose
integer

Enables several levels of logging during automation: 0: limited to no logging, 1: SDK-level logging, 2: LLM-client level logging (most granular)

llmClient
LLMClient

A custom LLM client implementation that conforms to the LLMClient abstract class

systemPrompt
string

A custom system prompt to use for the LLM in addition to the default system prompt for act, extract, and observe methods.

selfHeal
boolean

Enables self-healing mode. When set to true, Stagehand will attempt to recover from errors (eg. outdated cached element not resolving) by retrying the last action. Defaults to true. Set to false to disable LLM inference on cache errors.

localBrowserLaunchOptions
LocalBrowserLaunchOptions

Provides comprehensive options for local browser instances.

Returns: Stagehand object

The constructor returns an instance of the Stagehand class configured with the specified options. However, to use Stagehand, you must still initialize it with init().

stagehand.init()

await stagehand.init();

init() asynchronously initializes the Stagehand instance. It should be called before any other methods.

stagehand.close()

await stagehand.close();

close() is a cleanup method to remove the temporary files created by Stagehand. It’s recommended that you call this explicitly when you’re done with your automation.