Skip to main content

⚠️ No longer maintained

The official Stagehand Python source has moved here. Documentation can be found here

This version of the Stagehand Python SDK is no longer maintained and will not receive updates, bug fixes, or security patches.

The AI Browser Automation Framework
Read the Docs

MIT License Discord Community

[![PyPI version](https://img.shields.io/pypi/v/stagehand.svg?label=pypi%20(stable))](https://pypi.org/project/stagehand/)

browserbase%2Fstagehand | Trendshift

If you're looking for other languages, you can find them here

Vibe code Stagehand with Director Director

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

# install from PyPI
uv pip install stagehand

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

Set your environment variables (from examples/.env.example):

  • MODEL_API_KEY
  • BROWSERBASE_API_KEY
cp examples/.env.example examples/.env
# Edit examples/.env with your credentials.

The examples load examples/.env automatically.

Examples and dependencies:

  • examples/full_example.py: stagehand only
  • examples/act_example.py: stagehand only
  • examples/agent_execute.py: stagehand only
  • examples/local_example.py: stagehand only
  • examples/logging_example.py: stagehand only
  • examples/remote_browser_playwright_example.py: Playwright + Playwright browsers
  • examples/local_browser_playwright_example.py: Playwright + Playwright browsers
  • examples/playwright_page_example.py: Playwright + Playwright browsers
  • examples/byob_example.py: Playwright + Playwright browsers
  • examples/pydoll_tab_example.py: pydoll-python (Python 3.10+)

Multiregion support: see examples/local_server_multiregion_browser_example.py.

Run any example:

uv run python examples/remote_browser_playwright_example.py

Usage

This mirrors examples/remote_browser_playwright_example.py.

import os

from playwright.sync_api import sync_playwright

from env import load_example_env
from stagehand import Stagehand


def main() -> None:
    load_example_env()

    with Stagehand(
        server="remote",
        browserbase_api_key=os.environ.get("BROWSERBASE_API_KEY"),
        model_api_key=os.environ.get("MODEL_API_KEY"),
    ) as client:
        session = client.sessions.start(
            model_name="anthropic/claude-sonnet-4-6",
            browser={"type": "browserbase"},
        )

        cdp_url = session.data.cdp_url
        if not cdp_url:
            raise RuntimeError("No cdp_url returned from the API for this session.")

        with sync_playwright() as p:
            browser = p.chromium.connect_over_cdp(cdp_url)
            context = browser.contexts[0] if browser.contexts else browser.new_context()
            page = context.pages[0] if context.pages else context.new_page()

            client.sessions.navigate(session.id, url="https://news.ycombinator.com")
            page.wait_for_load_state("domcontentloaded")

            observe_stream = client.sessions.observe(
                session.id,
                instruction="find the link to view comments for the top post",
                stream_response=True,
                x_stream_response="true",
            )
            for _ in observe_stream:
                pass

            act_stream = client.sessions.act(
                session.id,
                input="Click the comments link for the top post",
                stream_response=True,
                x_stream_response="true",
            )
            for _ in act_stream:
                pass

            extract_stream = client.sessions.extract(
                session.id,
                instruction="extract the text of the top comment on this page",
                schema={
                    "type": "object",
                    "properties": {
                        "commentText": {"type": "string"},
                        "author": {"type": "string"},
                    },
                    "required": ["commentText"],
                },
                stream_response=True,
                x_stream_response="true",
            )
            for _ in extract_stream:
                pass

            execute_stream = client.sessions.execute(
                session.id,
                execute_options={
                    "instruction": "Click the 'Learn more' link if available",
                    "max_steps": 3,
                },
                agent_config={
                    "model": {"model_name": "anthropic/claude-opus-4-6"},
                    "cua": False,
                },
                stream_response=True,
                x_stream_response="true",
            )
            for _ in execute_stream:
                pass

        client.sessions.end(session.id)


if __name__ == "__main__":
    main()

Client configuration

Configure the client using environment variables:

from stagehand import AsyncStagehand

client = AsyncStagehand()

Or manually:

from stagehand import AsyncStagehand

client = AsyncStagehand(
    browserbase_api_key="My Browserbase API Key",
    model_api_key="My Model API Key",
)

Or using a combination of the two approaches:

from stagehand import AsyncStagehand

client = AsyncStagehand(
    # Configures using environment variables
    browserbase_api_key="My Browserbase API Key",  # override just this one
)

See this table for the available options:

Keyword argument Environment variable Required Default value
browserbase_api_key BROWSERBASE_API_KEY true -
browserbase_project_id - false -
model_api_key MODEL_API_KEY true -
base_url STAGEHAND_API_URL false "https://api.stagehand.browserbase.com"

browserbase_project_id is deprecated, accepted for backwards compatibility, and ignored. STAGEHAND_BASE_URL remains supported as a deprecated fallback when STAGEHAND_API_URL is unset.

Keyword arguments take precedence over environment variables.

Modifying configuration

To temporarily use a modified client configuration while reusing the same connection pool, call with_options() on any client:

client_with_options = client.with_options(model_api_key="sk-your-llm-api-key-here", max_retries=42)

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:

import asyncio
from stagehand import AsyncStagehand


async def main() -> None:
    client = AsyncStagehand()
    session = await client.sessions.start(model_name="anthropic/claude-sonnet-4-6")
    response = await session.act(input="click the first link on the page")
    print(response.data)


asyncio.run(main())

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:

# install from PyPI
uv pip install stagehand[aiohttp]

Then instantiate the client with http_client=DefaultAioHttpClient():

import asyncio
from stagehand import AsyncStagehand, DefaultAioHttpClient


async def main() -> None:
    async with AsyncStagehand(http_client=DefaultAioHttpClient()) as client:
        session = await client.sessions.start(model_name="anthropic/claude-sonnet-4-6")
        response = await session.act(input="click the first link on the page")
        print(response.data)


asyncio.run(main())

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.
import asyncio

from stagehand import AsyncStagehand


async def main() -> None:
    async with AsyncStagehand() as client:
        session = await client.sessions.start(model_name="anthropic/claude-sonnet-4-6")

        stream = await client.sessions.act(
            id=session.id,
            input="click the first link on the page",
            stream_response=True,
            x_stream_response="true",
        )
        async for event in stream:
            # event is a StreamEvent (type: "system" | "log")
            print(event.type, event.data)


asyncio.run(main())

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:

import asyncio

from stagehand import AsyncStagehand


async def main() -> None:
    async with AsyncStagehand() as client:
        response = await client.sessions.with_raw_response.start(model_name="anthropic/claude-sonnet-4-6")
        print(response.headers.get("X-My-Header"))

        session = response.parse()  # get the object that `sessions.start()` would have returned
        print(session.data)


asyncio.run(main())

.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().

import asyncio

from stagehand import AsyncStagehand


async def main() -> None:
    async with AsyncStagehand() as client:
        async with client.sessions.with_streaming_response.start(model_name="anthropic/claude-sonnet-4-6") as response:
            print(response.headers.get("X-My-Header"))
            async for line in response.iter_lines():
                print(line)


asyncio.run(main())

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.

import asyncio

import stagehand
from stagehand import AsyncStagehand


async def main() -> None:
    async with AsyncStagehand() as client:
        try:
            await client.sessions.start(model_name="anthropic/claude-sonnet-4-6")
        except stagehand.APIConnectionError as e:
            print("The server could not be reached")
            print(e.__cause__)  # an underlying Exception, likely raised within httpx.
        except stagehand.RateLimitError:
            print("A 429 status code was received; we should back off a bit.")
        except stagehand.APIStatusError as e:
            print("A non-200-range status code was received")
            print(e.status_code)
            print(e.response)


asyncio.run(main())

Error codes are as follows:

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 the max_retries option to configure or disable retry settings:

import asyncio

from stagehand import AsyncStagehand


async def main() -> None:
    async with AsyncStagehand(max_retries=0) as client:
        # Or, configure per-request:
        await client.with_options(max_retries=5).sessions.start(model_name="anthropic/claude-sonnet-4-6")


asyncio.run(main())

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:

export STAGEHAND_LOG=info

Or to debug for more verbose logging:

export STAGEHAND_LOG=debug

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.

import httpx
from stagehand import AsyncStagehand

import asyncio


async def main() -> None:
    async with AsyncStagehand() as client:
        response = await client.post("/foo", cast_to=httpx.Response, body={"my_param": True})
        print(response.headers.get("x-foo"))


asyncio.run(main())

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.

import asyncio

from stagehand import APIResponseValidationError, AsyncStagehand

try:
    async def main() -> None:
        async with AsyncStagehand(_strict_response_validation=True) as client:
            await client.sessions.start(model_name="anthropic/claude-sonnet-4-6")

    asyncio.run(main())
except APIResponseValidationError as e:
    print("Response failed schema validation:", e)

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:

if response.my_field is None:
    if "my_field" not in response.model_fields_set:
        print('Got json like {}, without a "my_field" key present at all.')
    else:
        print('Got json like {"my_field": null}.')

Accessing raw response data (e.g. headers)

The "raw" Response object can be accessed by prefixing .with_raw_response. to any HTTP method call, e.g.,

from stagehand import Stagehand

client = Stagehand()
response = client.sessions.with_raw_response.start(
    model_name="anthropic/claude-sonnet-4-6",
)
print(response.headers.get('X-My-Header'))

session = response.parse()  # get the object that `sessions.start()` would have returned
print(session.data)

These methods return an APIResponse object.

The async client returns an AsyncAPIResponse with the same structure, the only difference being awaitable methods for reading the response content.

.with_streaming_response

The above interface eagerly reads the full response body when you make the request, which may not always be what you want.

To stream the response body, use .with_streaming_response instead, which requires a context manager and only reads the response body once you call .read(), .text(), .json(), .iter_bytes(), .iter_text(), .iter_lines() or .parse(). In the async client, these are async methods.

with client.sessions.with_streaming_response.start(
    model_name="anthropic/claude-sonnet-4-6",
) as response:
    print(response.headers.get("X-My-Header"))

    for line in response.iter_lines():
        print(line)

The context manager is required so that the response will reliably be closed.

Making custom/undocumented requests

This library is typed for convenient access to the documented API.

If you need to access undocumented endpoints, params, or response properties, the library can still be used.

Undocumented endpoints

To make requests to undocumented endpoints, you can make requests using client.get, client.post, and other http verbs. Options on the client will be respected (such as retries) when making this request.

import httpx

response = client.post(
    "/foo",
    cast_to=httpx.Response,
    body={"my_param": True},
)

print(response.headers.get("x-foo"))

Undocumented request params

If you want to explicitly send an extra param, you can do so with the extra_query, extra_body, and extra_headers request options.

Undocumented response properties

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

Configuring the HTTP client

You can directly override the httpx client to customize it for your use case, including:

import httpx
from stagehand import Stagehand, DefaultHttpxClient

client = Stagehand(
    # Or use the `STAGEHAND_API_URL` env var, with `STAGEHAND_BASE_URL` as a fallback
    base_url="http://my.test.server.example.com:8083",
    http_client=DefaultHttpxClient(
        proxy="http://my.test.proxy.example.com",
        transport=httpx.HTTPTransport(local_address="0.0.0.0"),
    ),
)

You can also customize the client on a per-request basis by using with_options():

client.with_options(http_client=DefaultHttpxClient(...))

Managing HTTP resources

By default the library closes underlying HTTP connections whenever the client is garbage collected. You can manually close the client using the .close() method if desired, or with a context manager that closes when exiting.

from stagehand import Stagehand

with Stagehand() as client:
  # make requests here
  ...

# HTTP client is now closed

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:

import stagehand

print(stagehand.__version__)

Metadata

Release files for stagehand 3.23.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for stagehand 3.23.1
File Size Uploaded Provenance Actions
stagehand-3.23.1.tar.gz 290.7 kB Without provenance Details for stagehand-3.23.1.tar.gz

Built distributions (wheels)

Table of built distributions (wheels) for stagehand 3.23.1
File Actions
stagehand-3.23.1-py3-none-win_amd64.whl Python 3 none Windows x86-64 Details for stagehand-3.23.1-py3-none-win_amd64.whl
stagehand-3.23.1-py3-none-manylinux2014_x86_64.whl Python 3 none Linux glibc 2.17+ x86-64 Details for stagehand-3.23.1-py3-none-manylinux2014_x86_64.whl
stagehand-3.23.1-py3-none-macosx_11_0_arm64.whl Python 3 none macOS 11.0+ ARM64 Details for stagehand-3.23.1-py3-none-macosx_11_0_arm64.whl
stagehand-3.23.1-py3-none-macosx_10_9_x86_64.whl Python 3 none macOS 10.9+ x86-64 Details for stagehand-3.23.1-py3-none-macosx_10_9_x86_64.whl

Total release size: 171.2 MB

Release files / stagehand-3.23.1.tar.gz

Download URL stagehand-3.23.1.tar.gz
Size 290.7 kB
Tags Source
SHA-256 checksum
How to use checksums
7696ec5f4d6fadf4f347337af7689d9dc3239a50a3fbc14826e0e6ed501629ce
BLAKE2b-256 checksum
How to use checksums
168c0d27e237922a32b5a79cdd1a8038264a83f67a900477d3b91b254fceb3a9
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.9.13 {"installer":{"name":"uv","version":"0.9.13"},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / stagehand-3.23.1-py3-none-win_amd64.whl

Download URL stagehand-3.23.1-py3-none-win_amd64.whl
Size 38.1 MB
Tags Python 3 Windows x86-64
SHA-256 checksum
How to use checksums
1bf02c668a7155df9f989c222435d28137d29690ca4f43a4ed2befe18cc3295c
BLAKE2b-256 checksum
How to use checksums
5c685b21d5e6cd1367ad4ca3a767b5719dc8c57e7bd7c2d17ffc8ac5d892fefe
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.9.13 {"installer":{"name":"uv","version":"0.9.13"},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / stagehand-3.23.1-py3-none-manylinux2014_x86_64.whl

Download URL stagehand-3.23.1-py3-none-manylinux2014_x86_64.whl
Size 46.4 MB
Tags Linux glibc 2.17+ x86-64 Python 3
SHA-256 checksum
How to use checksums
eba9f70712215a62fa0f6bbb60ac268ff93bb961fb279eaacab5b09323602f95
BLAKE2b-256 checksum
How to use checksums
c77f2fda6d043219708894f5874d684b6daf41d557b84fe432e675be1c324533
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.9.13 {"installer":{"name":"uv","version":"0.9.13"},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / stagehand-3.23.1-py3-none-macosx_11_0_arm64.whl

Download URL stagehand-3.23.1-py3-none-macosx_11_0_arm64.whl
Size 42.5 MB
Tags Python 3 macOS 11.0+ ARM64
SHA-256 checksum
How to use checksums
ae1a9be3b28553214e0ae8f44a9f498dbc041e743311339f23b40fc2bf32f1f9
BLAKE2b-256 checksum
How to use checksums
241c4c1419019c273d0df9c7c68f3dcd86a45a7e61f1552b5078c10d60359e64
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.9.13 {"installer":{"name":"uv","version":"0.9.13"},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / stagehand-3.23.1-py3-none-macosx_10_9_x86_64.whl

Download URL stagehand-3.23.1-py3-none-macosx_10_9_x86_64.whl
Size 43.9 MB
Tags Python 3 macOS 10.9+ x86-64
SHA-256 checksum
How to use checksums
c2439dd4d7a2c44ddcf88bfe8a8cbd9131b88948522b26ea4e9e9b0410086115
BLAKE2b-256 checksum
How to use checksums
16276021ce0f6dbaa032bd0d25ff32d8420dc0ea8a6f152b42ea9115a7932a51
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.9.13 {"installer":{"name":"uv","version":"0.9.13"},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for stagehand 3.23.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

3.23.1 This release

5 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page