The official Python library for the stagehand API
Project description
Stagehand Python API Library
The Stagehand Python SDK provides convenient access to the Stagehand REST API from applications written in Python.
It is generated with Stainless.
Installation
pip install stagehand-alpha
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:
export BROWSERBASE_API_KEY="your-bb-api-key"
export BROWSERBASE_PROJECT_ID="your-bb-project-uuid"
export MODEL_API_KEY="sk-proj-your-llm-api-key"
python examples/full_example.py
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.
from stagehand import Stagehand, __version__
def main() -> None:
sdk_version = __version__
# Create client using environment variables:
# BROWSERBASE_API_KEY, BROWSERBASE_PROJECT_ID, MODEL_API_KEY
client = Stagehand()
# Start a new browser session
start_response = client.sessions.start(
model_name="openai/gpt-5-nano",
x_language="python",
x_sdk_version=sdk_version,
)
session_id = start_response.data.session_id
print(f"Session started: {session_id}")
try:
# Navigate to a webpage
client.sessions.navigate(
id=session_id,
url="https://news.ycombinator.com",
frame_id="", # empty string for the main frame
x_language="python",
x_sdk_version=sdk_version,
)
print("Navigated to Hacker News")
# Observe to find possible actions on the page
observe_response = client.sessions.observe(
id=session_id,
instruction="find the link to view comments for the top post",
x_language="python",
x_sdk_version=sdk_version,
)
results = observe_response.data.result
print(f"Found {len(results)} possible actions")
if not results:
return
# Take the first action returned by Observe and pass it to Act
action = results[0].to_dict(exclude_none=True)
print("Acting on:", action.get("description"))
act_response = client.sessions.act(
id=session_id,
input=action,
x_language="python",
x_sdk_version=sdk_version,
)
print("Act completed:", act_response.data.result.message)
# Extract structured data from the page using a JSON schema
extract_response = client.sessions.extract(
id=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"],
},
x_language="python",
x_sdk_version=sdk_version,
)
extracted = extract_response.data.result
author = extracted.get("author", "unknown") if isinstance(extracted, dict) else "unknown"
print("Extracted author:", author)
# Run an autonomous agent to accomplish a complex task
execute_response = client.sessions.execute(
id=session_id,
execute_options={
"instruction": f"Find any personal website, GitHub, or LinkedIn profile for the Hacker News user '{author}'.",
"max_steps": 10,
},
agent_config={"model": "openai/gpt-5-nano"},
x_language="python",
x_sdk_version=sdk_version,
timeout=300.0,
)
print("Agent completed:", execute_response.data.result.message)
print("Agent success:", execute_response.data.result.success)
finally:
# End the browser session to clean up resources
client.sessions.end(id=session_id, x_language="python", x_sdk_version=sdk_version)
print("Session ended")
if __name__ == "__main__":
main()
Client configuration
Configure the client using environment variables:
from stagehand import Stagehand
client = Stagehand()
Or manually:
from stagehand import Stagehand
client = Stagehand(
browserbase_api_key="My Browserbase API Key",
browserbase_project_id="My Browserbase Project ID",
model_api_key="My Model API Key",
)
Or using a combination of the two approaches:
from stagehand import Stagehand
client = Stagehand(
# 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 |
BROWSERBASE_PROJECT_ID |
true | - |
model_api_key |
MODEL_API_KEY |
true | - |
base_url |
STAGEHAND_BASE_URL |
false | "https://api.stagehand.browserbase.com" |
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
The default client is synchronous. To switch to asynchronous execution, use AsyncStagehand and await each API call:
import asyncio
from stagehand import AsyncStagehand
async def main() -> None:
client = AsyncStagehand()
response = await client.sessions.act(
id="00000000-your-session-id-000000000000",
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:
pip install stagehand-alpha[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:
response = await client.sessions.act(
id="00000000-your-session-id-000000000000",
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:
- 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.
from stagehand import Stagehand
client = Stagehand()
stream = client.sessions.act(
id="00000000-your-session-id-000000000000",
input="click the first link on the page",
stream_response=True,
x_stream_response="true",
)
for event in stream:
# event is a StreamEvent (type: "system" | "log")
print(event.type, event.data)
The async client uses the exact same interface:
from stagehand import AsyncStagehand
client = AsyncStagehand()
stream = await client.sessions.act(
id="00000000-your-session-id-000000000000",
input="click the first link on the page",
stream_response=True,
x_stream_response="true",
)
async for event in stream:
print(event.type, event.data)
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:
from stagehand import Stagehand
client = Stagehand()
response = client.sessions.with_raw_response.start(model_name="openai/gpt-5-nano")
print(response.headers.get("X-My-Header"))
session = response.parse() # get the object that `sessions.start()` would have returned
print(session.data.session_id)
.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().
from stagehand import Stagehand
client = Stagehand()
with client.sessions.with_streaming_response.start(model_name="openai/gpt-5-nano") as response:
print(response.headers.get("X-My-Header"))
for line in response.iter_lines():
print(line)
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 stagehand
from stagehand import Stagehand
client = Stagehand()
try:
client.sessions.start(model_name="openai/gpt-5-nano")
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)
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:
from stagehand import Stagehand
# Configure the default for all requests:
client = Stagehand(max_retries=0)
# Or, configure per-request:
client.with_options(max_retries=5).sessions.start(model_name="openai/gpt-5-nano")
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 Stagehand
client = Stagehand()
response = client.post("/foo", cast_to=httpx.Response, body={"my_param": True})
print(response.headers.get("x-foo"))
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.
from stagehand import Stagehand, APIResponseValidationError
try:
with Stagehand(_strict_response_validation=True) as client:
client.sessions.start(model_name="openai/gpt-5-nano")
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}.')
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.
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
Built Distributions
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file stagehand_alpha-0.2.4.tar.gz.
File metadata
- Download URL: stagehand_alpha-0.2.4.tar.gz
- Upload date:
- Size: 243.1 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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
282fd99feb16c87afcc8fbd29bb2e7fab1eb56a1fd8fcb03aea02297b54d8413
|
|
| MD5 |
5fa41976de5edc90600ce8d8601ffb19
|
|
| BLAKE2b-256 |
2606db018578e6a236802f1afe1f598dd5e6e6c58126c3d06bbd75bc5cdab1d9
|
File details
Details for the file stagehand_alpha-0.2.4-py3-none-win_amd64.whl.
File metadata
- Download URL: stagehand_alpha-0.2.4-py3-none-win_amd64.whl
- Upload date:
- Size: 98.6 kB
- 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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
10d62f6f0a3e6ac9bc09258677dfcb6ab4ea06934a98aba165d99698719621eb
|
|
| MD5 |
19d9c3d70578b85775fc82a29b0bf1a7
|
|
| BLAKE2b-256 |
fd72d8c34bbf6b3a71f254949c05e047b3597a059572ec3b2b3dabd156853b33
|
File details
Details for the file stagehand_alpha-0.2.4-py3-none-manylinux2014_x86_64.whl.
File metadata
- Download URL: stagehand_alpha-0.2.4-py3-none-manylinux2014_x86_64.whl
- Upload date:
- Size: 97.9 kB
- 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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
cfc2e4038a1bbf158c349e95cb32557441dace415f6ecf6b1e3b679a2dd4aa92
|
|
| MD5 |
7e05cccc5f8fa772e19c12657043e50b
|
|
| BLAKE2b-256 |
e4d2e32d26b686f87e475bfc03aa56e333a87d9b2a32aa7375d59302e97640f8
|
File details
Details for the file stagehand_alpha-0.2.4-py3-none-macosx_11_0_arm64.whl.
File metadata
- Download URL: stagehand_alpha-0.2.4-py3-none-macosx_11_0_arm64.whl
- Upload date:
- Size: 97.9 kB
- 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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
d1fdd081a65caaad6628103554a03b0d90d14f0b29d5c157c2cf544d028376ca
|
|
| MD5 |
3d4f26dce9990dd2c7d87f78340a8e76
|
|
| BLAKE2b-256 |
fb256dd80337cd94fc6d94bb96df17a932e25f53e887abc6e30051cbb638ec1b
|
File details
Details for the file stagehand_alpha-0.2.4-py3-none-macosx_10_9_x86_64.whl.
File metadata
- Download URL: stagehand_alpha-0.2.4-py3-none-macosx_10_9_x86_64.whl
- Upload date:
- Size: 97.9 kB
- 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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
edb50ac08b9fb1f4ff479f7f75095ad7a4d2b2025bc23ef9ebe37074355282d0
|
|
| MD5 |
5cd55827832a7b1fadcad70846765718
|
|
| BLAKE2b-256 |
399a52f1d34d540a036c066e0849fa83a133dba972054b472b096cbf735368c5
|