### Example .env File Configuration Source: https://github.com/browserbase/stagehand-python/blob/main/_autodocs/configuration.md An example of how to structure your .env file for authentication and optional configuration, including custom headers. ```bash # Authentication BROWSERBASE_API_KEY=bb_your_api_key_here MODEL_API_KEY=sk_your_model_key_here # Optional configuration STAGEHAND_API_URL=https://api.stagehand.example.com STAGEHAND_LOG=debug # Custom headers STAGEHAND_CUSTOM_HEADERS="X-API-Version: v3 X-Custom-Header: value" ``` -------------------------------- ### Sync Dependencies with uv Source: https://github.com/browserbase/stagehand-python/blob/main/CONTRIBUTING.md Install dependencies using uv after manual installation. Ensure uv is installed manually before running. ```sh $ uv sync --all-extras ``` -------------------------------- ### Copy .env.example to .env Source: https://github.com/browserbase/stagehand-python/blob/main/CLAUDE.md Copy the example environment file to .env and edit it with your credentials. This file is automatically loaded by the examples. ```bash cp examples/.env.example examples/.env # Edit examples/.env with your credentials. ``` -------------------------------- ### Build and Install from Source Source: https://github.com/browserbase/stagehand-python/blob/main/CONTRIBUTING.md Build a distributable version of the library (wheel file) and then install it. This process creates files in the `dist/` directory. ```sh $ uv build # or $ uv run python -m build ``` ```sh uv run pip install ./path-to-wheel-file.whl ``` -------------------------------- ### Asynchronous Session Start and Act Source: https://github.com/browserbase/stagehand-python/blob/main/CLAUDE.md Demonstrates how to start a new session and perform an action using the asynchronous client. ```APIDOC ## AsyncStagehand.sessions.start and AsyncStagehand.Session.act ### Description Initiates a new session with a specified model and then performs an action within that session. ### Method - `client.sessions.start(model_name: str)`: Asynchronously starts a new session. - `session.act(input: str)`: Asynchronously performs an action within the current session. ### Parameters #### `client.sessions.start` - **model_name** (str) - Required - The name of the model to use for the session (e.g., "anthropic/claude-sonnet-4-6"). #### `session.act` - **input** (str) - Required - The action or prompt to send to the model. ### Request Example ```python 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()) ``` ### Response #### Success Response (200) - **data** (str) - The response data from the model. ``` -------------------------------- ### AsyncStagehand Example Usage Source: https://github.com/browserbase/stagehand-python/blob/main/_autodocs/api-reference/stagehand-client.md Demonstrates how to use the AsyncStagehand client to start a session, perform an action, and print the response data. Ensure you replace placeholder API keys with your actual credentials. ```python import asyncio from stagehand import AsyncStagehand async def main(): async with AsyncStagehand( browserbase_api_key="YOUR_BROWSERBASE_API_KEY", model_api_key="YOUR_MODEL_API_KEY" ) as client: session = await client.sessions.start(model_name="anthropic/claude-sonnet-4-6") response = await session.act(input="click the first link") print(response.data) asyncio.run(main()) ``` -------------------------------- ### Install aiohttp Backend for Stagehand Source: https://github.com/browserbase/stagehand-python/blob/main/_autodocs/configuration.md Install the aiohttp extra for Stagehand to enable its use as an async HTTP client. ```bash pip install stagehand[aiohttp] ``` -------------------------------- ### Add and Run Examples Source: https://github.com/browserbase/stagehand-python/blob/main/CONTRIBUTING.md Add custom examples to the `examples/` directory. Make them executable and run them against your API. The shebang line `#!/usr/bin/env -S uv run python` ensures they are run within the uv environment. ```python # add an example to examples/.py #!/usr/bin/env -S uv run python … ``` ```sh $ chmod +x examples/.py # run the example against your api $ ./examples/.py ``` -------------------------------- ### Run a Stagehand Example Source: https://github.com/browserbase/stagehand-python/blob/main/CLAUDE.md Execute any of the provided Stagehand examples using the `uv run` command. Ensure you have set up your environment variables. ```bash uv run python examples/remote_browser_playwright_example.py ``` -------------------------------- ### Full Stagehand Example with Playwright Source: https://github.com/browserbase/stagehand-python/blob/main/CLAUDE.md This example demonstrates a comprehensive workflow using Stagehand with Playwright for remote browser control. It includes starting a session, navigating, observing, acting, extracting data, and executing agent commands. Ensure your environment variables `BROWSERBASE_API_KEY` and `MODEL_API_KEY` are set. ```python 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() ``` -------------------------------- ### Install Stagehand with uv Source: https://github.com/browserbase/stagehand-python/blob/main/CLAUDE.md Install Stagehand from PyPI using the uv package manager. Ensure Python 3.9 or higher is used. ```sh uv pip install stagehand ``` -------------------------------- ### Install Stagehand with aiohttp Support Source: https://github.com/browserbase/stagehand-python/blob/main/CLAUDE.md To use `aiohttp` as the HTTP backend for improved concurrency, install the `stagehand` package with the `aiohttp` extra. This command installs the necessary dependencies. ```sh # install from PyPI uv pip install stagehand[aiohttp] ``` -------------------------------- ### start() - Start a new browser session Source: https://github.com/browserbase/stagehand-python/blob/main/_autodocs/api-reference/sessions-api.md Initiates a new browser session. You can specify the AI model, browser configuration, and various timeouts and experimental features. ```APIDOC ## start() ### Description Starts a new browser session. ### Method Signature **Sync:** ```python def start( self, *, model_name: str, act_timeout_ms: float | Omit = omit, browser: Browser | Omit = omit, browserbase_session_create_params: BrowserbaseSessionCreateParams | Omit = omit, browserbase_session_id: str | Omit = omit, dom_settle_timeout_ms: float | Omit = omit, experimental: bool | Omit = omit, self_heal: bool | Omit = omit, system_prompt: str | Omit = omit, verbose: Literal[0, 1, 2] | Omit = omit, wait_for_captcha_solves: bool | Omit = omit, x_stream_response: Literal["true", "false"] | Omit = omit, extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> Session ``` **Async:** ```python async def start( self, *, model_name: str, # ... same parameters ... ) -> AsyncSession ``` ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | model_name | str | true | — | AI model to use (e.g., "anthropic/claude-sonnet-4-6") | | browser | Browser | false | — | Browser configuration (type, launch options, or CDP URL) | | browserbase_session_create_params | BrowserbaseSessionCreateParams | false | — | Browserbase session creation parameters | | browserbase_session_id | str | false | — | Existing Browserbase session ID to resume | | dom_settle_timeout_ms | float | false | — | Timeout in milliseconds to wait for DOM to settle | | self_heal | bool | false | — | Enable self-healing for failed actions | | system_prompt | str | false | — | Custom system prompt for AI operations | | verbose | Literal[0, 1, 2] | false | — | Logging verbosity: 0=quiet, 1=normal, 2=debug | | act_timeout_ms | float | false | — | Timeout in ms for act operations (deprecated, v2 only) | | wait_for_captcha_solves | bool | false | — | Wait for captcha solves (deprecated, v2 only) | | experimental | bool | false | — | Enable experimental features | | x_stream_response | Literal["true", "false"] | false | — | Enable Server-Sent Events streaming | ### Return Type **Sync:** `Session` - Bound session object with session ID and data **Async:** `AsyncSession` - Async variant with same interface ### Session Fields | Field | Type | Description | |-------|------|-------------| | id | str | Unique session identifier | | success | bool | Whether the request was successful | | data.session_id | str | Browserbase session ID | | data.cdp_url | str | None | Chrome DevTools Protocol URL (when available) | | data.available | bool | Whether the session is available | ### Example ```python from stagehand import Stagehand client = Stagehand( browserbase_api_key="YOUR_API_KEY", model_api_key="YOUR_MODEL_KEY" ) # Create a session session = client.sessions.start( model_name="anthropic/claude-sonnet-4-6", browser={"type": "browserbase"}, verbose=1, ) print(f"Session ID: {session.id}") print(f"CDP URL: {session.data.cdp_url}") ``` ``` -------------------------------- ### Configuration Source: https://github.com/browserbase/stagehand-python/blob/main/_autodocs/index.md Information on client setup and customization, including constructor options, environment variables, HTTP client configuration, and logging setup. ```APIDOC ## Configuration ### Description Provides details on how to set up and customize the Stagehand Python SDK client. ### Configuration Methods - **Constructor Options**: Parameters available when initializing the client. - **Environment Variables**: SDK behavior controlled via environment variables. - **HTTP Client Configuration**: Settings for the underlying HTTP client. - **Logging Setup**: How to configure logging for the SDK. ``` -------------------------------- ### Synchronous Client Initialization and Usage Source: https://github.com/browserbase/stagehand-python/blob/main/_autodocs/README.md Demonstrates how to initialize the synchronous Stagehand client and start a session to perform actions. ```APIDOC ## Synchronous Client Initialization and Usage ### Description This section shows how to set up and use the synchronous `Stagehand` client for blocking code execution. It includes starting a session and performing an action. ### Method ```python from stagehand import Stagehand client = Stagehand( browserbase_api_key="YOUR_KEY", model_api_key="YOUR_MODEL_KEY" ) session = client.sessions.start(model_name="anthropic/claude-sonnet-4-6") response = session.act(input="click the button") ``` ### Parameters - `browserbase_api_key` (string) - Required - API key for Browserbase. - `model_api_key` (string) - Required - API key for the language model. - `model_name` (string) - Required - The name of the model to use for the session. - `input` (string) - Required - The action or query to perform. ``` -------------------------------- ### Basic Session Initialization and Usage Source: https://github.com/browserbase/stagehand-python/blob/main/_autodocs/index.md Demonstrates how to initialize a synchronous Stagehand client and start a new session to interact with a model. Remember to replace placeholder API keys with your actual credentials. ```python from stagehand import Stagehand client = Stagehand( browserbase_api_key="YOUR_API_KEY", model_api_key="YOUR_MODEL_KEY" ) session = client.sessions.start(model_name="anthropic/claude-sonnet-4-6") response = session.act(input="click the login button") session.end() ``` -------------------------------- ### Install from Git Source: https://github.com/browserbase/stagehand-python/blob/main/CONTRIBUTING.md Install the Stagehand Python package directly from its Git repository using uv. This is useful for development or when you need the latest unreleased changes. ```sh $ uv run pip install git+ssh://git@github.com/browserbase/stagehand-python.git ``` -------------------------------- ### Start Session Source: https://github.com/browserbase/stagehand-python/blob/main/_autodocs/api-reference/sessions-api.md Starts a new browser session and returns a bound session object. This object allows direct method calls for session interactions. ```APIDOC ## Start Session ### Description Starts a new browser session with a specified model and returns a bound session object. ### Method `client.sessions.start(model_name: str, ...)` ### Parameters #### Query Parameters - **model_name** (string) - Required - The name of the model to use for the session. ### Response #### Success Response - **Session** or **AsyncSession** object - A bound session object with the session ID pre-populated. ### Request Example ```python session = client.sessions.start(model_name="anthropic/claude-sonnet-4-6") ``` ``` -------------------------------- ### Streaming Responses with SSE Source: https://github.com/browserbase/stagehand-python/blob/main/AGENTS.md This example demonstrates how to enable and handle Server-Sent Events (SSE) for streaming responses from the Stagehand API. It shows how to start a session and then stream events back to the client. ```APIDOC ## Streaming Responses with SSE To enable SSE streaming, you must set `x_stream_response="true"` in the request headers and `stream_response=True` in the client call. ### Method POST (implied by `client.sessions.act`) ### Endpoint (Not explicitly defined, but related to session actions) ### Parameters #### Request Body (for `client.sessions.act`) - **id** (string) - Required - The session ID. - **input** (string) - Required - The user input or prompt. - **stream_response** (boolean) - Required - Set to `True` to enable client-side streaming. - **x_stream_response** (string) - Required - Set to `"true"` to enable server-side SSE streaming. ### Request Example ```python await client.sessions.act( id=session.id, input="click the first link on the page", stream_response=True, x_stream_response="true", ) ``` ### Response - **stream** (AsyncIterator[StreamEvent]) - An asynchronous iterator yielding `StreamEvent` objects. - **StreamEvent.type** (string) - Type of the event (`"system"` or `"log"`). - **StreamEvent.data** (any) - The event data. ### Response Example ```python async for event in stream: print(event.type, event.data) ``` ``` -------------------------------- ### SessionStartParams Source: https://github.com/browserbase/stagehand-python/blob/main/_autodocs/types.md Parameters for starting a new session. Includes model selection, timeouts, and session configuration. ```APIDOC ## SessionStartParams ### Description Parameters for starting a new session. ### Parameters #### Fields - **model_name** (str) - Required - Model name to use for AI operations - **act_timeout_ms** (float) - Optional - Timeout in ms for act operations (deprecated, v2 only) - **browser** (Browser) - Optional - Browser object - **browserbase_session_create_params** (BrowserbaseSessionCreateParams) - Optional - Browserbase session creation parameters - **browserbase_session_id** (str) - Optional - Existing Browserbase session ID to resume - **dom_settle_timeout_ms** (float) - Optional - Timeout in ms to wait for DOM to settle - **experimental** (bool) - Optional - **self_heal** (bool) - Optional - Enable self-healing for failed actions - **system_prompt** (str) - Optional - Custom system prompt for AI operations - **verbose** (Literal[0, 1, 2]) - Optional - Logging verbosity level (0=quiet, 1=normal, 2=debug) - **wait_for_captcha_solves** (bool) - Optional - Wait for captcha solves (deprecated, v2 only) - **x_stream_response** (Literal["true", "false"]) - Optional - Whether to stream the response via SSE ``` -------------------------------- ### Configure Stagehand for Long-Running Applications with aiohttp Source: https://github.com/browserbase/stagehand-python/blob/main/_autodocs/configuration.md Utilize `AsyncStagehand` with `aiohttp` for long-running applications requiring high concurrency. This example demonstrates starting multiple sessions concurrently. ```python from stagehand import AsyncStagehand, DefaultAioHttpClient async def main(): # Use aiohttp for better concurrency async with AsyncStagehand( http_client=DefaultAioHttpClient(), max_retries=3, ) as client: # Multiple concurrent operations tasks = [ client.sessions.start(model_name="anthropic/claude-sonnet-4-6") for _ in range(10) ] sessions = await asyncio.gather(*tasks) ``` -------------------------------- ### Start and Use a Bound Session Source: https://github.com/browserbase/stagehand-python/blob/main/_autodocs/api-reference/sessions-api.md Initiates a new session and demonstrates calling various methods directly on the returned session object. This is more convenient than repeatedly passing the session ID. ```python session = client.sessions.start(model_name="anthropic/claude-sonnet-4-6") response = session.navigate(url="https://example.com") response = session.act(input="click button") response = session.observe(instruction="describe the page") result = session.extract(instruction="extract data", schema={...}) response = session.execute(execute_options={...}, agent_config={...}) response = session.end() ``` -------------------------------- ### SessionStartResponse Source: https://github.com/browserbase/stagehand-python/blob/main/_autodocs/types.md Response from starting a browser session. ```APIDOC ## SessionStartResponse Response from starting a session. ```python class SessionStartResponse(BaseModel): success: bool """Indicates whether the request was successful""" data: SessionStartResponseData class SessionStartResponseData(BaseModel): session_id: str = Field(alias="sessionId") """Unique Browserbase session identifier""" available: bool """Whether the session is available""" cdp_url: str | None = Field(alias="cdpUrl", default=None) """CDP WebSocket URL (when available)""" ``` ``` -------------------------------- ### AsyncStagehand Basic Usage Source: https://github.com/browserbase/stagehand-python/blob/main/README.md Demonstrates the basic usage of the asynchronous Stagehand client to start a session and perform an action. ```APIDOC ## AsyncStagehand Basic Usage ### Description This example shows how to initialize the `AsyncStagehand` client, start a new session with a specified model, and then use the `act` method to perform an action within that session. The response data is then printed. ### Method `AsyncStagehand.sessions.start` and `Session.act` ### Endpoint N/A (SDK methods) ### Parameters #### `AsyncStagehand.sessions.start` - **model_name** (string) - Required - The name of the model to use for the session. #### `Session.act` - **input** (string) - Required - The action or input to send to the session. ### Request Example ```python 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()) ``` ### Response #### Success Response - **data** (object) - The data returned from the session's action. ``` -------------------------------- ### Start Session and Act with AsyncStagehand Source: https://github.com/browserbase/stagehand-python/blob/main/CLAUDE.md Use `AsyncStagehand` for asynchronous API calls. Instantiate the client and `await` session start and action methods. Ensure you run the `main` function within an asyncio event loop. ```python 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()) ``` -------------------------------- ### Basic Session Source: https://github.com/browserbase/stagehand-python/blob/main/_autodocs/index.md Start and manage a basic synchronous session to interact with a language model. ```APIDOC ## Basic Session ```python from stagehand import Stagehand client = Stagehand( browserbase_api_key="YOUR_API_KEY", model_api_key="YOUR_MODEL_KEY" ) session = client.sessions.start(model_name="anthropic/claude-sonnet-4-6") response = session.act(input="click the login button") session.end() ``` ``` -------------------------------- ### Start a New Browser Session (Sync) Source: https://github.com/browserbase/stagehand-python/blob/main/_autodocs/api-reference/sessions-api.md Initiates a new browser session using the Stagehand client. Specify the AI model and optionally configure browser settings and logging verbosity. This is used to create a new session for browser automation tasks. ```python from stagehand import Stagehand client = Stagehand( browserbase_api_key="YOUR_API_KEY", model_api_key="YOUR_MODEL_KEY" ) # Create a session session = client.sessions.start( model_name="anthropic/claude-sonnet-4-6", browser={"type": "browserbase"}, verbose=1, ) print(f"Session ID: {session.id}") print(f"CDP URL: {session.data.cdp_url}") ``` -------------------------------- ### Synchronous Stagehand Initialization and Action Source: https://github.com/browserbase/stagehand-python/blob/main/_autodocs/README.md Use this snippet for synchronous operations. It initializes the Stagehand client and starts a session to perform an action. ```python from stagehand import Stagehand client = Stagehand( browserbase_api_key="YOUR_KEY", model_api_key="YOUR_MODEL_KEY" ) session = client.sessions.start(model_name="anthropic/claude-sonnet-4-6") response = session.act(input="click the button") ``` -------------------------------- ### Start a Stagehand Session Source: https://github.com/browserbase/stagehand-python/blob/main/_autodocs/api-reference/stagehand-client.md Initiates a new Stagehand session using the provided API keys. Ensure you have your Browserbase and Model API keys ready. ```python from stagehand import Stagehand client = Stagehand( browserbase_api_key="YOUR_BROWSERBASE_API_KEY", model_api_key="YOUR_MODEL_API_KEY" ) session = client.sessions.start(model_name="anthropic/claude-sonnet-4-6") ``` -------------------------------- ### Initialize AsyncStagehand with aiohttp Backend Source: https://github.com/browserbase/stagehand-python/blob/main/_autodocs/api-reference/stagehand-client.md Use the AsyncStagehand client with an aiohttp backend for asynchronous operations. Requires `stagehand[aiohttp]` to be installed. The client is managed within an async context manager. ```python from stagehand import AsyncStagehand, DefaultAioHttpClient async with AsyncStagehand(http_client=DefaultAioHttpClient()) as client: session = await client.sessions.start(model_name="anthropic/claude-sonnet-4-6") ``` -------------------------------- ### HTTP Client Customization - With aiohttp Backend Source: https://github.com/browserbase/stagehand-python/blob/main/_autodocs/api-reference/stagehand-client.md Configure the Stagehand client to use an `aiohttp` backend for asynchronous operations. Requires `aiohttp` to be installed. ```APIDOC ## HTTP Client Customization - With aiohttp Backend (Async Only) ### Description Enables the use of an `aiohttp` backend for asynchronous HTTP requests. ### Requirements Requires installation: `pip install stagehand[aiohttp]` ### Example ```python from stagehand import AsyncStagehand, DefaultAioHttpClient async with AsyncStagehand(http_client=DefaultAioHttpClient()) as client: session = await client.sessions.start(model_name="anthropic/claude-sonnet-4-6") ``` ``` -------------------------------- ### Accessing Raw Responses Source: https://github.com/browserbase/stagehand-python/blob/main/AGENTS.md This example shows how to retrieve the raw HTTP response, including headers and status codes, using the `with_raw_response` prefix before making a client call. It also demonstrates how to parse the response body into a Pydantic model. ```APIDOC ## Accessing Raw Responses To access response headers, status code, and the raw response body, prefix the method call with `with_raw_response`. ### Method POST (implied by `client.sessions.start`) ### Endpoint (Not explicitly defined, but related to session start) ### Parameters #### Request Body (for `client.sessions.start`) - **model_name** (string) - Required - The name of the model to use. ### Request Example ```python response = await client.sessions.with_raw_response.start(model_name="anthropic/claude-sonnet-4-6") ``` ### Response - **response** (RawResponse) - An object containing the raw HTTP response details. - **response.headers** (Headers) - A dictionary-like object containing response headers. - **response.status_code** (int) - The HTTP status code. - **response.parse()** - Method to parse the response body into the expected Pydantic model. ### Response Example ```python print(response.headers.get("X-My-Header")) session = response.parse() print(session.data) ``` ``` -------------------------------- ### Streaming Raw Response Body (Non-SSE) Source: https://github.com/browserbase/stagehand-python/blob/main/AGENTS.md This example demonstrates how to stream the raw response body, distinct from SSE, using the `with_streaming_response` context manager. It allows for iterative reading of the response content. ```APIDOC ## Streaming Raw Response Body (Non-SSE) Use `with_streaming_response` to stream the response body. This requires a context manager and allows reading the body iteratively. ### Method POST (implied by `client.sessions.start`) ### Endpoint (Not explicitly defined, but related to session start) ### Parameters #### Request Body (for `client.sessions.start`) - **model_name** (string) - Required - The name of the model to use. ### Request Example ```python async with client.sessions.with_streaming_response.start(model_name="anthropic/claude-sonnet-4-6") as response: # ... process response ... ``` ### Response - **response** (StreamingResponse) - A context manager for streaming the response body. - **response.headers** (Headers) - A dictionary-like object containing response headers. - **response.iter_lines()** - Asynchronous iterator yielding lines from the response body. - **response.read()**, **response.text()**, **response.json()**, **response.iter_bytes()**, **response.iter_lines()**, **response.parse()** - Methods to consume the response body. ### Response Example ```python 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) ``` ``` -------------------------------- ### Handling ConflictError Source: https://github.com/browserbase/stagehand-python/blob/main/_autodocs/errors.md Example of catching a ConflictError, which signals a state conflict, such as attempting to start an already existing session. ```python try: client.sessions.start( model_name="anthropic/claude-sonnet-4-6", browserbase_session_id="existing-id" # Already in use ) except stagehand.ConflictError as e: print("Session already exists") ``` -------------------------------- ### Get Stagehand Python Version Source: https://github.com/browserbase/stagehand-python/blob/main/CLAUDE.md Use this snippet to print the installed version of the stagehand package at runtime. Ensure the stagehand library is imported first. ```python import stagehand print(stagehand.__version__) ``` -------------------------------- ### Async Session Initialization and Usage Source: https://github.com/browserbase/stagehand-python/blob/main/_autodocs/index.md Shows how to set up and use an asynchronous Stagehand client within an asyncio event loop. The `async with` statement ensures proper resource management for the client. ```python import asyncio from stagehand import AsyncStagehand async def main(): async with AsyncStagehand( browserbase_api_key="YOUR_API_KEY", model_api_key="YOUR_MODEL_KEY" ) as client: session = await client.sessions.start( model_name="anthropic/claude-sonnet-4-6" ) response = await session.act(input="search for python") await session.end() asyncio.run(main()) ``` -------------------------------- ### client.sessions.start Source: https://github.com/browserbase/stagehand-python/blob/main/api.md Initiates a new browser session. This is the entry point for creating new automated browsing instances. ```APIDOC ## POST /v1/sessions/start ### Description Initiates a new browser session. ### Method POST ### Endpoint /v1/sessions/start ### Parameters #### Request Body - **params** (object) - Required - Parameters for starting the session, such as browser configuration. ``` -------------------------------- ### Supported Options for with_options() Source: https://github.com/browserbase/stagehand-python/blob/main/_autodocs/configuration.md Demonstrates the various configuration options that can be passed to the `with_options()` method for customizing client behavior. ```python client.with_options( browserbase_api_key="new_key", model_api_key="new_model_key", server="local", base_url="https://custom-url.com", timeout=30.0, max_retries=5, default_headers={"X-Custom": "value"}, default_query={"param": "value"}, http_client=custom_client, ) ``` -------------------------------- ### Error Handling Examples Source: https://github.com/browserbase/stagehand-python/blob/main/_autodocs/README.md Provides examples of how to handle common exceptions raised by the Stagehand library, such as authentication and rate limit errors. ```APIDOC ## Error Handling Examples ### Description This section provides examples of how to catch and handle specific exceptions that may occur during Stagehand operations, such as authentication failures or rate limiting. ### Method ```python import stagehand try: session = client.sessions.start(...) except stagehand.AuthenticationError: print("Invalid API key") except stagehand.RateLimitError: print("Rate limited, retry later") ``` ### Exceptions Handled - `stagehand.AuthenticationError`: Raised when invalid API keys are provided. - `stagehand.RateLimitError`: Raised when the API rate limits are exceeded. ``` -------------------------------- ### BrowserLaunchOptions Type Source: https://github.com/browserbase/stagehand-python/blob/main/_autodocs/types.md Provides detailed configuration options for launching a browser instance, including arguments, timeouts, and viewport settings. ```APIDOC ## BrowserLaunchOptions Browser launch configuration options. ### Type Definition ```python class BrowserLaunchOptions(TypedDict, total=False): accept_downloads: bool args: list[str] cdp_headers: dict[str, str] cdp_url: str chromium_sandbox: bool connect_timeout_ms: float device_scale_factor: float devtools: bool downloads_path: str executable_path: str has_touch: bool headless: bool ignore_default_args: bool | list[str] ignore_https_errors: bool locale: str port: float preserve_user_data_dir: bool proxy: BrowserLaunchOptionsProxy user_data_dir: str viewport: BrowserLaunchOptionsViewport ``` ### Fields | Field | Type | Description | |-------|------|-------------| | accept_downloads | bool | Accept download prompts | | args | list[str] | Additional browser arguments | | cdp_headers | dict | Custom headers for CDP connections | | cdp_url | str | Connect to existing browser via CDP | | chromium_sandbox | bool | Enable Chromium sandbox | | connect_timeout_ms | float | Connection timeout in ms | | device_scale_factor | float | Device scale factor for rendering | | devtools | bool | Open DevTools on launch | | downloads_path | str | Path for downloaded files | | executable_path | str | Path to browser executable | | has_touch | bool | Emulate touch events | | headless | bool | Run in headless mode | | ignore_default_args | bool | list[str] | Ignore or override default args | | ignore_https_errors | bool | Ignore HTTPS errors | | locale | str | Browser locale (e.g., "en-US") | | port | float | Browser port | | preserve_user_data_dir | bool | Keep user data directory after close | | proxy | BrowserLaunchOptionsProxy | Proxy configuration | | user_data_dir | str | User data directory path | | viewport | BrowserLaunchOptionsViewport | Viewport dimensions | ### Used By - `Browser` - `SessionStartParams` ``` -------------------------------- ### Initialize AsyncStagehand with mixed configuration Source: https://github.com/browserbase/stagehand-python/blob/main/CLAUDE.md Instantiate the `AsyncStagehand` client using a mix of environment variables and manual overrides. Manual arguments take precedence. ```python from stagehand import AsyncStagehand client = AsyncStagehand( # Configures using environment variables browserbase_api_key="My Browserbase API Key", # override just this one ) ``` -------------------------------- ### Handle APIResponseValidationError Example Source: https://github.com/browserbase/stagehand-python/blob/main/_autodocs/errors.md Example of catching APIResponseValidationError when strict response validation is enabled. This demonstrates how to access error details like the message and status code. ```python client = Stagehand( _strict_response_validation=True, ) try: client.sessions.start(model_name="anthropic/claude-sonnet-4-6") except stagehand.APIResponseValidationError as e: print(f"Response validation failed: {e.message}") print(f"Status: {e.status_code}") ``` -------------------------------- ### Bootstrap Environment with uv Source: https://github.com/browserbase/stagehand-python/blob/main/CONTRIBUTING.md Use this command to automatically provision a Python environment with the expected Python version using uv. ```sh $ ./scripts/bootstrap ``` -------------------------------- ### Initialize AsyncStagehand with environment variables Source: https://github.com/browserbase/stagehand-python/blob/main/CLAUDE.md Instantiate the `AsyncStagehand` client. Configuration is automatically loaded from environment variables. ```python from stagehand import AsyncStagehand client = AsyncStagehand() ``` -------------------------------- ### Async Session Source: https://github.com/browserbase/stagehand-python/blob/main/_autodocs/index.md Start and manage an asynchronous session for non-blocking interactions with a language model. ```APIDOC ## Async Session ```python import asyncio from stagehand import AsyncStagehand async def main(): async with AsyncStagehand( browserbase_api_key="YOUR_API_KEY", model_api_key="YOUR_MODEL_KEY" ) as client: session = await client.sessions.start( model_name="anthropic/claude-sonnet-4-6" ) response = await session.act(input="search for python") await session.end() asyncio.run(main()) ``` ``` -------------------------------- ### Handling BadRequestError Source: https://github.com/browserbase/stagehand-python/blob/main/_autodocs/errors.md Example of catching a BadRequestError, typically raised for invalid or malformed requests. ```python try: client.sessions.start(model_name="") # Empty string except stagehand.BadRequestError as e: print(f"Invalid request: {e.message}") ``` -------------------------------- ### Asynchronous Client Initialization and Usage Source: https://github.com/browserbase/stagehand-python/blob/main/_autodocs/README.md Illustrates how to initialize and use the asynchronous `AsyncStagehand` client for non-blocking operations. ```APIDOC ## Asynchronous Client Initialization and Usage ### Description This section demonstrates the usage of the asynchronous `AsyncStagehand` client, suitable for non-blocking I/O operations. It shows initialization using an async context manager and starting a session. ### Method ```python from stagehand import AsyncStagehand import asyncio async with AsyncStagehand(...) as client: session = await client.sessions.start(...) response = await session.act(input="...") ``` ### Parameters - `browserbase_api_key` (string) - Required - API key for Browserbase. - `model_api_key` (string) - Required - API key for the language model. - `model_name` (string) - Required - The name of the model to use for the session. - `input` (string) - Required - The action or query to perform. ``` -------------------------------- ### sessions Source: https://github.com/browserbase/stagehand-python/blob/main/_autodocs/api-reference/stagehand-client.md Provides access to the SessionsResource for managing Stagehand sessions. Use this to start new sessions. ```APIDOC ## sessions ### Description Returns the sessions resource for managing Stagehand sessions. See [SessionsResource](#sessions-resource) for available methods. ### Method `sessions` (property) ### Example ```python from stagehand import Stagehand client = Stagehand( browserbase_api_key="YOUR_BROWSERBASE_API_KEY", model_api_key="YOUR_MODEL_API_KEY" ) session = client.sessions.start(model_name="anthropic/claude-sonnet-4-6") ``` ``` -------------------------------- ### Configure Local Stagehand Development Environment Source: https://github.com/browserbase/stagehand-python/blob/main/_autodocs/configuration.md Set up the Stagehand client for local development, including specifying the binary path, host, port, and browser settings. Set `local_headless=False` to view the browser. ```python client = Stagehand( server="local", _local_stagehand_binary_path="./stagehand-binary", local_host="localhost", local_port=3000, local_headless=False, # Show browser window local_chrome_path="/usr/bin/chromium", ) ``` -------------------------------- ### Handling PermissionDeniedError Source: https://github.com/browserbase/stagehand-python/blob/main/_autodocs/errors.md Example of catching a PermissionDeniedError, which occurs when the API key does not have the necessary permissions for an action. ```python try: client.sessions.start(model_name="anthropic/claude-sonnet-4-6") except stagehand.PermissionDeniedError as e: print("Your API key doesn't have permission for this action") ``` -------------------------------- ### Handling AuthenticationError Source: https://github.com/browserbase/stagehand-python/blob/main/_autodocs/errors.md Example of catching an AuthenticationError, which signals problems with API key validity or presence. ```python try: client = Stagehand(browserbase_api_key="invalid_key") client.sessions.start(model_name="anthropic/claude-sonnet-4-6") except stagehand.AuthenticationError as e: print("Check your API keys") ``` -------------------------------- ### Modify Client Options with with_options() Source: https://github.com/browserbase/stagehand-python/blob/main/_autodocs/configuration.md Create a new client instance with temporary configuration overrides without affecting the original client. This is useful for making short-lived changes to settings like timeouts. ```python # Original client client = Stagehand(timeout=60.0) # Temporary override (doesn't affect original) client_fast = client.with_options(timeout=10.0) response = client_fast.sessions.start(...) # Original client still has 60s timeout response = client.sessions.start(...) ``` -------------------------------- ### Initialize Stagehand (Synchronous) Source: https://github.com/browserbase/stagehand-python/blob/main/_autodocs/configuration.md Instantiate the synchronous Stagehand client with API keys and server configuration. Ensure API keys are provided for authentication. ```python from stagehand import Stagehand client = Stagehand( browserbase_api_key="YOUR_API_KEY", model_api_key="YOUR_MODEL_KEY", server="remote", # or "local" base_url="https://api.stagehand.browserbase.com", timeout=60.0, max_retries=2, ) ``` -------------------------------- ### Handling APIStatusError Source: https://github.com/browserbase/stagehand-python/blob/main/_autodocs/errors.md Example of how to catch and handle a general APIStatusError, printing the status code and response text. ```python try: client.sessions.start(model_name="anthropic/claude-sonnet-4-6") except stagehand.APIStatusError as e: print(f"Status: {e.status_code}") print(f"Response: {e.response.text}") ``` -------------------------------- ### Initialize Stagehand Client with Environment Variables Source: https://github.com/browserbase/stagehand-python/blob/main/_autodocs/api-reference/stagehand-client.md Instantiate the Stagehand client. It automatically reads BROWSERBASE_API_KEY and MODEL_API_KEY from environment variables for authentication. ```python import os # These will be read from environment client = Stagehand() # Uses BROWSERBASE_API_KEY and MODEL_API_KEY ``` -------------------------------- ### Client Constructor Source: https://github.com/browserbase/stagehand-python/blob/main/_autodocs/index.md Instantiate the Stagehand client with various configuration options, including API keys, server settings, and timeouts. ```APIDOC ## Client Constructor ```python Stagehand( browserbase_api_key: str | None = None, # From BROWSERBASE_API_KEY model_api_key: str | None = None, # From MODEL_API_KEY server: Literal["remote", "local"] = "remote", base_url: str | httpx.URL | None = None, # From STAGEHAND_API_URL timeout: float | Timeout | None = not_given, # 60 seconds default max_retries: int = 2, default_headers: Mapping[str, str] | None = None, default_query: Mapping[str, object] | None = None, http_client: httpx.Client | None = None, _strict_response_validation: bool = False, ) ``` See [Configuration](configuration.md) for all options. ``` -------------------------------- ### Browser Type Source: https://github.com/browserbase/stagehand-python/blob/main/_autodocs/types.md Defines the browser configuration for a session start request. It specifies the browser type and connection details. ```APIDOC ## Browser Browser configuration for a session start request. ### Type Definition ```python class Browser(TypedDict, total=False): type: Literal["local", "browserbase"] """Browser type to use""" cdp_url: str """Chrome DevTools Protocol URL for connecting to existing browser""" launch_options: BrowserLaunchOptions ``` ### Used By - `SessionStartParams` ``` -------------------------------- ### Configure Stagehand for Development Source: https://github.com/browserbase/stagehand-python/blob/main/_autodocs/configuration.md Set up Stagehand for development with a quick timeout, no retries, and a local base URL for immediate feedback. ```python from stagehand import Stagehand import logging logging.basicConfig(level=logging.DEBUG) client = Stagehand( timeout=30.0, # Quick feedback during development max_retries=0, # See failures immediately base_url="http://localhost:3000", # Local server ) ``` -------------------------------- ### Download Local Server Binary Source: https://github.com/browserbase/stagehand-python/blob/main/CONTRIBUTING.md Automatically download the correct Stagehand server binary for your platform and architecture. The script places the binary in `bin/sea/`. ```sh $ uv run python scripts/download_binary.py ``` -------------------------------- ### client.sessions.observe Source: https://github.com/browserbase/stagehand-python/blob/main/api.md Starts observing the browser session for specific events or changes. This can be used for monitoring or reacting to dynamic content. ```APIDOC ## POST /v1/sessions/{id}/observe ### Description Starts observing the browser session for specific events or changes. ### Method POST ### Endpoint /v1/sessions/{id}/observe ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the session. #### Request Body - **params** (object) - Required - Parameters specifying what to observe. ``` -------------------------------- ### copy / with_options Source: https://github.com/browserbase/stagehand-python/blob/main/_autodocs/api-reference/stagehand-client.md Creates a new client instance with modified options, reusing the connection pool. `with_options()` is an alias for `copy()`. ```APIDOC ## copy / with_options ### Description Creates a new client instance with modified options while reusing the connection pool. `with_options()` is an alias for `copy()`. ### Method `copy` or `with_options` (method) ### Parameters - All parameters are optional. - `set_default_headers` and `set_default_query` replace rather than merge default values. ### Returns New `Stagehand` instance with merged options. ### Example ```python # Reuse connection pool with different timeout client_with_timeout = client.with_options(timeout=30.0) session = client_with_timeout.sessions.start(model_name="anthropic/claude-opus-4-6") # Use different API key temporarily client_with_alt_key = client.with_options(model_api_key="sk-different-key") ``` ``` -------------------------------- ### SessionStartResponse Type Definition Source: https://github.com/browserbase/stagehand-python/blob/main/_autodocs/types.md Defines the response structure for starting a browser session, indicating success and providing session details. ```python class SessionStartResponse(BaseModel): success: bool """Indicates whether the request was successful""" data: SessionStartResponseData class SessionStartResponseData(BaseModel): session_id: str = Field(alias="sessionId") """Unique Browserbase session identifier""" available: bool """Whether the session is available""" cdp_url: str | None = Field(alias="cdpUrl", default=None) """CDP WebSocket URL (when available)""" ``` -------------------------------- ### Handle InternalServerError Source: https://github.com/browserbase/stagehand-python/blob/main/_autodocs/errors.md Example of catching and handling an InternalServerError during an API call. This error is automatically retried up to 2 times by default. ```python try: client.sessions.start(model_name="anthropic/claude-sonnet-4-6") except stagehand.InternalServerError as e: print(f"Server error {e.status_code}: {e.message}") ``` -------------------------------- ### Enable Info Logging Source: https://github.com/browserbase/stagehand-python/blob/main/CLAUDE.md Set the STAGEHAND_LOG environment variable to 'info' to enable standard logging. ```sh export STAGEHAND_LOG=info ``` -------------------------------- ### Handling UnprocessableEntityError Source: https://github.com/browserbase/stagehand-python/blob/main/_autodocs/errors.md Example of catching an UnprocessableEntityError, which can occur due to issues like an invalid JSON schema provided in the request. ```python try: response = session.extract( instruction="extract data", schema={"invalid": "schema"} # Invalid JSON Schema ) except stagehand.UnprocessableEntityError as e: print(f"Invalid schema: {e.message}") ``` -------------------------------- ### AsyncStagehand with aiohttp Source: https://github.com/browserbase/stagehand-python/blob/main/CLAUDE.md Shows how to instantiate the asynchronous client using aiohttp as the HTTP backend for improved concurrency. ```APIDOC ## AsyncStagehand with aiohttp HTTP Client ### Description Instantiates the `AsyncStagehand` client using `aiohttp` as the underlying HTTP client for potentially better performance in concurrent scenarios. ### Method - `AsyncStagehand(http_client=DefaultAioHttpClient())`: Initializes the client with `aiohttp` support. ### Parameters - **http_client** (DefaultAioHttpClient) - Optional - The HTTP client to use. Defaults to `httpx` if not provided. Use `DefaultAioHttpClient()` for `aiohttp` integration. ### Request Example ```python 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()) ``` ### Installation To use `aiohttp`, install it with the `aiohttp` extra: ```sh # install from PyPI uv pip install stagehand[aiohttp] ``` ``` -------------------------------- ### Handling NotFoundError Source: https://github.com/browserbase/stagehand-python/blob/main/_autodocs/errors.md Example of catching a NotFoundError, useful when trying to access a non-existent resource like an invalid session ID. ```python try: client.sessions.navigate("invalid-session-id", url="https://example.com") except stagehand.NotFoundError as e: print(f"Session not found: {e.message}") ```