Skip to main content

The official Python library for the stagehand API

Project description

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.tw.martin98.com/project/stagehand/)

browserbase%2Fstagehand | Trendshift

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

Vibe code Stagehand with Director Director

[!TIP] 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

# 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.

[!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:

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__)

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

stagehand-3.20.0.tar.gz (284.0 kB view details)

Uploaded Source

Built Distributions

If you're not sure about the file name format, learn more about wheel file names.

stagehand-3.20.0-py3-none-win_amd64.whl (30.8 MB view details)

Uploaded Python 3Windows x86-64

stagehand-3.20.0-py3-none-manylinux2014_x86_64.whl (37.3 MB view details)

Uploaded Python 3

stagehand-3.20.0-py3-none-macosx_11_0_arm64.whl (33.2 MB view details)

Uploaded Python 3macOS 11.0+ ARM64

stagehand-3.20.0-py3-none-macosx_10_9_x86_64.whl (34.5 MB view details)

Uploaded Python 3macOS 10.9+ x86-64

File details

Details for the file stagehand-3.20.0.tar.gz.

File metadata

  • Download URL: stagehand-3.20.0.tar.gz
  • Upload date:
  • Size: 284.0 kB
  • Tags: Source
  • Uploaded using 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}

File hashes

Hashes for stagehand-3.20.0.tar.gz
Algorithm Hash digest
SHA256 c862f2da2ed0ed958ca5c8aec743bcfecf4a944336cf30df68a715f1c18a4abb
MD5 ed58e9c83ecaf213b7fbe04c1588497f
BLAKE2b-256 9b1bf703463a04a227f10c19a1f79c0311597a7a374ad02065e2294eb54ebaef

See more details on using hashes here.

File details

Details for the file stagehand-3.20.0-py3-none-win_amd64.whl.

File metadata

  • Download URL: stagehand-3.20.0-py3-none-win_amd64.whl
  • Upload date:
  • Size: 30.8 MB
  • Tags: Python 3, Windows x86-64
  • Uploaded using 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}

File hashes

Hashes for stagehand-3.20.0-py3-none-win_amd64.whl
Algorithm Hash digest
SHA256 110f231246847220e3e5fc06565042e6024e5fdc7094e4f6dd0328c63abd4c94
MD5 c99cb9fad63f619eccf5f00c5b758000
BLAKE2b-256 fa328140daf343c9c150bc88a96d82c4540b6ae1f96c5cb0d4d89fcc1c438426

See more details on using hashes here.

File details

Details for the file stagehand-3.20.0-py3-none-manylinux2014_x86_64.whl.

File metadata

  • Download URL: stagehand-3.20.0-py3-none-manylinux2014_x86_64.whl
  • Upload date:
  • Size: 37.3 MB
  • Tags: Python 3
  • Uploaded using 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}

File hashes

Hashes for stagehand-3.20.0-py3-none-manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 69cecb87b9f672e435f7297ab96dd6e81f23a4ec65bf0e5c00ce66a6b4601965
MD5 92fef480f03ab0ff47f054db049d45ed
BLAKE2b-256 7a5beb9623fa7e8627ed74b8f3f90e4076d29fb41531108b5141a966f9ff4a5f

See more details on using hashes here.

File details

Details for the file stagehand-3.20.0-py3-none-macosx_11_0_arm64.whl.

File metadata

  • Download URL: stagehand-3.20.0-py3-none-macosx_11_0_arm64.whl
  • Upload date:
  • Size: 33.2 MB
  • Tags: Python 3, macOS 11.0+ ARM64
  • Uploaded using 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}

File hashes

Hashes for stagehand-3.20.0-py3-none-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 72943f6056b0554770c54dabbce62ad9da1eb24ca1bf70da312e63a0802881c7
MD5 dae4a9549c51dd9016f13c2f286cd522
BLAKE2b-256 22b7bab837635ed381e5f1f3fbfa9636ec2670ca71727b720d4a00c69aebb46e

See more details on using hashes here.

File details

Details for the file stagehand-3.20.0-py3-none-macosx_10_9_x86_64.whl.

File metadata

  • Download URL: stagehand-3.20.0-py3-none-macosx_10_9_x86_64.whl
  • Upload date:
  • Size: 34.5 MB
  • Tags: Python 3, macOS 10.9+ x86-64
  • Uploaded using 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}

File hashes

Hashes for stagehand-3.20.0-py3-none-macosx_10_9_x86_64.whl
Algorithm Hash digest
SHA256 03a9dbd4b5952106e0685d51c6879a14306d3172367400daee4954c0581e2e54
MD5 41f8fc763839adffd55ef5e1dcab72c9
BLAKE2b-256 30bfa000e0d54009831e099a3d8dd0277ad638a15d0b4ead3a7d32d75677508b

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page