Skip to main content
This documentation is automatically synced from the Python SDK GitHub repository.
Migrating from the old v2 Python SDK? See our migration guide here.

What is Stagehand?

Stagehand is a browser automation framework used to control web browsers with natural language and code. By combining the power of AI with the precision of code, Stagehand makes web automation flexible, maintainable, and actually reliable.

Why Stagehand?

Most existing browser automation tools either require you to write low-level code in a framework like Selenium, Playwright, or Puppeteer, or use high-level agents that can be unpredictable in production. By letting developers choose what to write in code vs. natural language (and bridging the gap between the two) Stagehand is the natural choice for browser automations in production.
  1. Choose when to write code vs. natural language: use AI when you want to navigate unfamiliar pages, and use code when you know exactly what you want to do.
  2. Go from AI-driven to repeatable workflows: Stagehand lets you preview AI actions before running them, and also helps you easily cache repeatable actions to save time and tokens.
  3. Write once, run forever: Stagehand’s auto-caching combined with self-healing remembers previous actions, runs without LLM inference, and knows when to involve AI whenever the website changes and your automation breaks.

Installation

For local development or when working from this repository, sync the dependency lockfile with uv (see the Local development section below) before running project scripts.

Requirements

Python 3.9 or higher.

Running the Example

A complete working example is available at examples/full_example.py. To run it, first export the required environment variables, then use Python:

Local mode example

If you want to run Stagehand locally, use the local example (examples/local_example.py). It shows how to configure the client for server="local". Local mode runs Stagehand’s embedded server and launches a local Chrome/Chromium browser (it is not bundled with the Python wheel), so you must have Chrome installed on the machine running the example. If Chrome is installed but Stagehand can’t find it, set CHROME_PATH to your browser executable (or pass browser.launchOptions.executablePath when starting the session). Common Windows paths:
  • C:\Program Files\Google\Chrome\Application\chrome.exe
  • C:\Program Files (x86)\Google\Chrome\Application\chrome.exe
PowerShell:

Streaming logging example

See examples/logging_example.py for a remote-only flow that streams StreamEvents with verbose=2, stream_response=True, and x_stream_response="true" so you can watch the SDK’s logs as they arrive.

Usage

This example demonstrates the full Stagehand workflow: starting a session, navigating to a page, observing possible actions, acting on elements, extracting data, and running an autonomous agent.

Client configuration

Configure the client using environment variables:
Or manually:
Or using a combination of the two approaches:
See this table for the available options: Keyword arguments take precedence over environment variables.
[!TIP] Don’t create more than one client in the same application. Each client has a connection pool, which is more efficient to share between requests.

Modifying configuration

To temporarily use a modified client configuration while reusing the same connection pool, call with_options() on any client:
The with_options() method does not affect the original client.

Requests and responses

To send a request to the Stagehand API, call the corresponding client method using keyword arguments. Nested request parameters are dictionaries typed using TypedDict. Responses are Pydantic models which also provide helper methods like:
  • Serializing back into JSON: model.to_json()
  • Converting to a dictionary: model.to_dict()

Immutability

Response objects are Pydantic models. If you want to build a modified copy, prefer model.model_copy(update={...}) (Pydantic v2) rather than mutating in place.

Asynchronous execution

This SDK recommends using AsyncStagehand and awaiting each API call:

With aiohttp

By default, the async client uses httpx for HTTP requests. For improved concurrency performance you may also use aiohttp as the HTTP backend. Install aiohttp:
Then instantiate the client with http_client=DefaultAioHttpClient():

Streaming responses

We provide support for streaming responses using Server-Sent Events (SSE). To enable SSE streaming, you must:
  1. Ask the server to stream by setting x_stream_response="true" (header), and
  2. Tell the client to parse an SSE stream by setting stream_response=True.

Raw responses

The SDK defines methods that deserialize responses into Pydantic models. However, these methods don’t provide access to response headers, status code, or the raw response body. To access this data, prefix any HTTP method call on a client or service with with_raw_response:

.with_streaming_response

The with_raw_response interface eagerly reads the full response body when you make the request. To stream the response body (not SSE), use with_streaming_response instead. It requires a context manager and only reads the response body once you call .read(), .text(), .json(), .iter_bytes(), .iter_text(), .iter_lines() or .parse().

Error handling

When the library is unable to connect to the API (for example, due to network connection problems or a timeout), a subclass of stagehand.APIConnectionError is raised. When the API returns a non-success status code (that is, 4xx or 5xx response), a subclass of stagehand.APIStatusError is raised, containing status_code and response properties. All errors inherit from stagehand.APIError.
Error codes are as follows:

Retries

Certain errors are automatically retried 2 times by default, with a short exponential backoff. Connection errors (for example, due to a network connectivity problem), 408 Request Timeout, 409 Conflict, 429 Rate Limit, and >=500 Internal errors are all retried by default. You can use the max_retries option to configure or disable retry settings:

Timeouts

By default requests time out after 1 minute. You can configure this with a timeout option, which accepts a float or an httpx.Timeout object. On timeout, an APITimeoutError is thrown. Note that requests that time out are retried twice by default.

Logging

The SDK uses the standard library logging module. Enable logging by setting the STAGEHAND_LOG environment variable to info:
Or to debug for more verbose logging:

Undocumented API functionality

This library is typed for convenient access to the documented API, but you can still access undocumented endpoints, request params, or response properties when needed.

Undocumented endpoints

To make requests to undocumented endpoints, use client.get, client.post, and other HTTP verbs. Client options (such as retries) are respected.

Undocumented request params

To send extra params that aren’t available as keyword args, use extra_query, extra_body, and extra_headers.

Undocumented response properties

To access undocumented response properties, you can access extra fields like response.unknown_prop. You can also get all extra fields as a dict with response.model_extra.

Response validation

In rare cases, the API may return a response that doesn’t match the expected type. By default, the SDK is permissive and will only raise an error if you later try to use the invalid data. If you would prefer to validate responses upfront, instantiate the client with _strict_response_validation=True. An APIResponseValidationError will be raised if the API responds with invalid data for the expected schema.

FAQ

Why are some values typed as Literal[...] instead of Python Enums?

Using Literal[...] types is forwards compatible: the API can introduce new enum values without breaking older SDKs at runtime.

How can I tell whether None means null or “missing” in a response?

In an API response, a field may be explicitly null, or missing entirely; in either case its value is None in this library. You can differentiate the two cases with .model_fields_set:

Semantic versioning

This package generally follows SemVer conventions, though certain backwards-incompatible changes may be released as minor versions:
  1. Changes that only affect static types, without breaking runtime behavior.
  2. Changes to library internals which are technically public but not intended or documented for external use. (Please open a GitHub issue to let us know if you are relying on such internals.)
  3. Changes that we do not expect to impact the vast majority of users in practice.
We take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience. We are keen for your feedback; please open an issue with questions, bugs, or suggestions.

Determining the installed version

If you’ve upgraded to the latest version but aren’t seeing any new features you were expecting then your python environment is likely still using an older version. You can determine the version that is being used at runtime with: