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.- 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.
- 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.
- 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
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 atexamples/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.exeC:\Program Files (x86)\Google\Chrome\Application\chrome.exe
Streaming logging example
Seeexamples/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:| Keyword argument | Environment variable | Required | Default value |
|---|---|---|---|
browserbase_api_key | BROWSERBASE_API_KEY | true | - |
browserbase_project_id | BROWSERBASE_PROJECT_ID | true | - |
model_api_key | MODEL_API_KEY | true | - |
base_url | STAGEHAND_BASE_URL | false | "https://api.stagehand.browserbase.com" |
[!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, callwith_options() on any client:
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 usingTypedDict. 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, prefermodel.model_copy(update={...}) (Pydantic v2) rather than mutating in place.
Asynchronous execution
This SDK recommends usingAsyncStagehand and awaiting each API call:
With aiohttp
By default, the async client useshttpx for HTTP requests. For improved concurrency performance you may also use aiohttp as the HTTP backend.
Install aiohttp:
http_client=DefaultAioHttpClient():
Streaming responses
We provide support for streaming responses using Server-Sent Events (SSE). To enable SSE streaming, you must:- Ask the server to stream by setting
x_stream_response="true"(header), and - 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 withwith_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 ofstagehand.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.
| Status Code | Error Type |
|---|---|
| 400 | BadRequestError |
| 401 | AuthenticationError |
| 403 | PermissionDeniedError |
| 404 | NotFoundError |
| 422 | UnprocessableEntityError |
| 429 | RateLimitError |
| >=500 | InternalServerError |
| N/A | APIConnectionError |
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 themax_retries option to configure or disable retry settings:
Timeouts
By default requests time out after 1 minute. You can configure this with atimeout 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 librarylogging module.
Enable logging by setting the STAGEHAND_LOG environment variable to info:
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, useclient.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, useextra_query, extra_body, and extra_headers.
Undocumented response properties
To access undocumented response properties, you can access extra fields likeresponse.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:- Changes that only affect static types, without breaking runtime behavior.
- 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.)
- Changes that we do not expect to impact the vast majority of users in practice.

