### Install Dependencies and Run Basic Example Source: https://docs.stagehand.dev/v3/sdk/ruby Installs project dependencies using Bundler and executes a basic Ruby example script. ```bash bundle install bundle exec ruby examples/basic.rb ``` -------------------------------- ### Navigate and Run Stagehand Example Source: https://docs.stagehand.dev/first-steps/quickstart After creating the project, navigate into the project directory, copy the environment file, and start the example script using npm. ```bash cd my-stagehand-app # Enter the project directory cp .env.example .env # Add your API keys npm start # Run the example script ``` -------------------------------- ### Set up and run a Stagehand project Source: https://docs.stagehand.dev/v3/first-steps/quickstart After creating the project, navigate into the directory, copy the environment file, and start the example script. Ensure your API keys are set in the .env file. ```bash cd my-stagehand-app # Enter the project directory cp .env.example .env # Add your API keys npm start # Run the example script ``` -------------------------------- ### Run Go Example Source: https://docs.stagehand.dev/v3/sdk/go Execute the main Go example file using `go run` to start the automated browser session and perform the defined tasks. ```bash go run examples/basic.go ``` -------------------------------- ### Run Local Mode Example Source: https://docs.stagehand.dev/v3/sdk/python Run the local mode example script using uv after installing the Stagehand SDK. ```bash uv pip install stagehand uv run python examples/local_example.py ``` -------------------------------- ### Basic Stagehand Setup with Browserbase Source: https://docs.stagehand.dev/configuration/browser Initialize Stagehand with default settings for the Browserbase environment. This is the simplest way to get started with cloud-managed browser infrastructure. ```javascript import { Stagehand } from "@browserbasehq/stagehand"; const stagehand = new Stagehand({ env: "BROWSERBASE", }); await stagehand.init(); ``` -------------------------------- ### Basic Stagehand Setup with Browserbase Source: https://docs.stagehand.dev/v3/configuration/browser Initialize Stagehand with default settings for Browserbase. This is the simplest way to get started. ```typescript import { Stagehand } from "@browserbasehq/stagehand"; const stagehand = new Stagehand({ env: "BROWSERBASE", }); await stagehand.init(); ``` -------------------------------- ### Install Google SDK with bun Source: https://docs.stagehand.dev/configuration/models Install the Vercel AI SDK for Google using bun. ```bash bun add @ai-sdk/google ``` -------------------------------- ### Install Dependencies and Build Project Source: https://docs.stagehand.dev/v3/integrations/mcp/setup Run this command to install necessary project dependencies and build the project. ```bash npm install && npm run build ``` -------------------------------- ### Install Google SDK with npm Source: https://docs.stagehand.dev/configuration/models Install the Vercel AI SDK for Google using npm. ```bash npm install @ai-sdk/google ``` -------------------------------- ### Install Google SDK with pnpm Source: https://docs.stagehand.dev/configuration/models Install the Vercel AI SDK for Google using pnpm. ```bash pnpm add @ai-sdk/google ``` -------------------------------- ### Install Google SDK with yarn Source: https://docs.stagehand.dev/configuration/models Install the Vercel AI SDK for Google using yarn. ```bash yarn add @ai-sdk/google ``` -------------------------------- ### Install Chrome (Windows) Source: https://docs.stagehand.dev/v3/sdk/python Optional step to install Google Chrome using winget if it's not already installed on Windows. ```powershell # optional if you don't already have Chrome installed winget install -e --id Google.Chrome ``` -------------------------------- ### Install Stagehand, Selenium, and Browserbase SDK Source: https://docs.stagehand.dev/v3/integrations/selenium Install the necessary npm packages for Stagehand, Selenium, and the Browserbase SDK. Ensure you have Node.js and npm installed. ```bash npm install @browserbasehq/stagehand selenium-webdriver @browserbasehq/sdk ``` -------------------------------- ### Install Stagehand SDK Source: https://docs.stagehand.dev/v3/sdk/python Install the Stagehand SDK using uv pip. Ensure you have uv installed for dependency management. ```bash uv pip install stagehand ``` -------------------------------- ### Run Streaming Logging Example Source: https://docs.stagehand.dev/v3/sdk/python Execute the logging example script using uv to observe streamed SDK logs. ```bash uv run examples/logging_example.py ``` -------------------------------- ### Install Vercel CLI (bun) Source: https://docs.stagehand.dev/v3/best-practices/deployments Installs the Vercel CLI globally using bun. Ensure bun is installed and configured. ```bash bun add -g vercel ``` -------------------------------- ### Install Google SDK Source: https://docs.stagehand.dev/v3/configuration/models Install the Vercel AI SDK for Google using npm, pnpm, yarn, or bun. ```bash npm install @ai-sdk/google ``` ```bash pnpm add @ai-sdk/google ``` ```bash yarn add @ai-sdk/google ``` ```bash bun add @ai-sdk/google ``` -------------------------------- ### Set Environment Variables and Run Full Example Source: https://docs.stagehand.dev/v3/sdk/python Set necessary API keys as environment variables and then run the full example script using uv. ```bash export BROWSERBASE_API_KEY="your-bb-api-key" export MODEL_API_KEY="sk-proj-your-llm-api-key" uv run python examples/full_example.py ``` -------------------------------- ### Environment Variables and Running the Example Source: https://docs.stagehand.dev/v3/sdk/java Export the necessary API keys and run the Stagehand Java example application using Gradle. ```bash export BROWSERBASE_API_KEY="your-bb-api-key" export MODEL_API_KEY="sk-proj-your-llm-api-key" ./gradlew :stagehand-java-example:run ``` -------------------------------- ### Full Stagehand Workflow in Java Source: https://docs.stagehand.dev/v3/sdk/java This example demonstrates the complete Stagehand workflow: starting a session, navigating to a page, observing possible actions, acting on elements, extracting data, and running an autonomous agent. It requires BROWSERBASE_API_KEY and MODEL_API_KEY environment variables to be set. ```java import com.browserbase.api.client.StagehandClient; import com.browserbase.api.client.okhttp.StagehandOkHttpClient; import com.browserbase.api.core.JsonValue; import com.browserbase.api.models.sessions.*; import java.util.List; import java.util.Map; import java.util.Optional; public class Main { public static void main(String[] args) { // Create client using environment variables: // BROWSERBASE_API_KEY, MODEL_API_KEY StagehandClient client = StagehandOkHttpClient.fromEnv(); // Start a new browser session SessionStartResponse startResponse = client.sessions().start( SessionStartParams.builder() .modelName("openai/gpt-5-nano") .build() ); String sessionId = startResponse.data().sessionId(); System.out.println("Session started: " + sessionId); try { // Navigate to a webpage client.sessions().navigate( SessionNavigateParams.builder() .id(sessionId) .url("https://news.ycombinator.com") .build() ); System.out.println("Navigated to Hacker News"); // Observe to find possible actions on the page SessionObserveResponse observeResponse = client.sessions().observe( SessionObserveParams.builder() .id(sessionId) .instruction("find the link to view comments for the top post") .build() ); List results = observeResponse.data().result(); System.out.println("Found " + results.size() + " possible actions"); if (results.isEmpty()) { System.out.println("No actions found"); return; } // Take the first action returned by Observe // Convert the result to an Action to pass to Act SessionObserveResponse.Data.Result result = results.get(0); Action action = JsonValue.from(result).convert(Action.class); System.out.println("Acting on: " + action.description()); // Pass the structured action to Act SessionActResponse actResponse = client.sessions().act( SessionActParams.builder() .id(sessionId) .input(action) .build() ); System.out.println("Act completed: " + actResponse.data().result().message()); // Extract structured data from the page using a JSON schema SessionExtractResponse extractResponse = client.sessions().extract( SessionExtractParams.builder() .id(sessionId) .instruction("extract the text of the top comment on this page") .schema(SessionExtractParams.Schema.builder() .putAdditionalProperty("type", JsonValue.from("object")) .putAdditionalProperty("properties", JsonValue.from(Map.of( "commentText", Map.of( "type", "string", "description", "The text content of the top comment" ), "author", Map.of( "type", "string", "description", "The username of the comment author" ) ))) .putAdditionalProperty("required", JsonValue.from(List.of("commentText"))) .build()) .build() ); JsonValue extractedResult = extractResponse.data()._result(); System.out.println("Extracted data: " + extractedResult); // Get the author from the extracted data String author = extractedResult.asObject() .flatMap(obj -> Optional.ofNullable(obj.get("author"))) .flatMap(JsonValue::asString) .orElse("unknown"); System.out.println("Looking up profile for author: " + author); // Run an autonomous agent to accomplish a complex task SessionExecuteResponse executeResponse = client.sessions().execute( SessionExecuteParams.builder() .id(sessionId) .executeOptions(SessionExecuteParams.ExecuteOptions.builder() .instruction(String.format( "Find any personal website, GitHub, or LinkedIn profile for user '%s'. " + "Click on their username to view their profile page.", author)) .build()) .build() ); System.out.println("Execute completed: " + executeResponse.data().result().message()); } catch (Exception e) { System.err.println("An error occurred: " + e.getMessage()); e.printStackTrace(); } finally { // End the session try { client.sessions().end(sessionId); System.out.println("Session ended: " + sessionId); } catch (Exception e) { System.err.println("Failed to end session: " + e.getMessage()); } } } } ``` -------------------------------- ### Install Amazon Bedrock SDK with bun Source: https://docs.stagehand.dev/configuration/models Install the Vercel AI SDK for Amazon Bedrock using bun. ```bash bun add @ai-sdk/amazon-bedrock ``` -------------------------------- ### Full Advanced Browserbase Configuration Example Source: https://docs.stagehand.dev/configuration/browser A comprehensive example demonstrating advanced Browserbase session configuration, including proxies, region, timeouts, keep-alive, detailed browser settings, and user metadata. ```javascript const stagehand = new Stagehand({ env: "BROWSERBASE", apiKey: process.env.BROWSERBASE_API_KEY, browserbaseSessionCreateParams: { proxies: true, region: "us-west-2", timeout: 3600, // 1 hour session timeout keepAlive: true, // Available on Startup plan browserSettings: { advancedStealth: false, // this is a Scale Plan feature - reach out to support@browserbase.com to enable blockAds: true, solveCaptchas: true, recordSession: false, viewport: { width: 1920, height: 1080, }, }, userMetadata: { userId: "automation-user-123", environment: "production", }, }, }); ``` -------------------------------- ### Install Stagehand and Playwright Source: https://docs.stagehand.dev/v3/integrations/playwright Install both Stagehand and Playwright using npm. This is the first step to integrating them. ```bash npm install @browserbasehq/stagehand playwright-core ``` -------------------------------- ### Install Vercel CLI with npm Source: https://docs.stagehand.dev/integrations/vercel/configuration Use this command to install the Vercel CLI globally using npm. ```bash npm add -g vercel ``` -------------------------------- ### Verify Stagehand CLI Installation Source: https://docs.stagehand.dev/v3/basics/evals Check if the Stagehand CLI is installed correctly by running the help command. ```bash evals help ``` -------------------------------- ### Install Amazon Bedrock SDK with pnpm Source: https://docs.stagehand.dev/configuration/models Install the Vercel AI SDK for Amazon Bedrock using pnpm. ```bash pnpm add @ai-sdk/amazon-bedrock ``` -------------------------------- ### Install Vercel CLI with pnpm Source: https://docs.stagehand.dev/integrations/vercel/configuration Use this command to install the Vercel CLI globally using pnpm. ```bash pnpm add -g vercel ``` -------------------------------- ### Install Amazon Bedrock SDK with yarn Source: https://docs.stagehand.dev/configuration/models Install the Vercel AI SDK for Amazon Bedrock using yarn. ```bash yarn add @ai-sdk/amazon-bedrock ``` -------------------------------- ### Install Amazon Bedrock SDK with npm Source: https://docs.stagehand.dev/configuration/models Install the Vercel AI SDK for Amazon Bedrock using npm. ```bash npm install @ai-sdk/amazon-bedrock ``` -------------------------------- ### Install Stagehand with aiohttp Support Source: https://docs.stagehand.dev/v3/sdk/python Installs the Stagehand SDK with aiohttp support for improved concurrency. This command should be run in your terminal. ```bash uv run pip install stagehand[aiohttp] ``` -------------------------------- ### Install Vercel CLI with yarn Source: https://docs.stagehand.dev/integrations/vercel/configuration Use this command to install the Vercel CLI globally using yarn. ```bash yarn add -g vercel ``` -------------------------------- ### Complete Stagehand and Playwright Example Source: https://docs.stagehand.dev/v3/integrations/playwright A full example demonstrating Stagehand initialization, Playwright connection, navigation, AI-powered observation, data extraction, and cleanup. Includes verbose logging. ```typescript import { Stagehand } from "@browserbasehq/stagehand"; import { chromium } from "playwright-core"; import { z } from "zod"; async function main() { // Initialize Stagehand const stagehand = new Stagehand({ env: "BROWSERBASE", model: "openai/gpt-5", verbose: 1, }); await stagehand.init(); console.log("Stagehand initialized"); // Connect Playwright to Stagehand's browser const browser = await chromium.connectOverCDP({ wsEndpoint: stagehand.connectURL(), }); const pwContext = browser.contexts()[0]; const pwPage = pwContext.pages()[0]; // Navigate and interact await pwPage.goto("https://example.com"); // Use Stagehand's AI methods const actions = await stagehand.observe("find the main heading", { page: pwPage, }); console.log("Found actions:", actions); // Extract data const heading = await stagehand.extract( "extract the main heading text", z.object({ heading: z.string() }), { page: pwPage } ); console.log("Heading:", heading); // Cleanup await stagehand.close(); } main(); ``` -------------------------------- ### Local STDIO Server Start Source: https://docs.stagehand.dev/v3/integrations/mcp/configuration Command to start the local MCP server using Node.js on a specified port. ```bash # Start server node cli.js --port 8931 ``` -------------------------------- ### LLM Inference Summary File Example Source: https://docs.stagehand.dev/configuration/logging Example structure of a 'Summary File' which aggregates all LLM calls with metrics like prompt tokens, completion tokens, and inference time. ```json { "act_summary": [ { "act_inference_type": "act", "timestamp": "20250127_123456", "LLM_input_file": "20250127_123456_act_call.txt", "LLM_output_file": "20250127_123456_act_response.txt", "prompt_tokens": 3451, "completion_tokens": 45, "inference_time_ms": 951 }, { "act_inference_type": "act", "timestamp": "20250127_123501", "LLM_input_file": "20250127_123501_act_call.txt", "LLM_output_file": "20250127_123501_act_response.txt", "prompt_tokens": 2890, "completion_tokens": 38, "inference_time_ms": 823 } ] } ``` -------------------------------- ### Install Amazon Bedrock SDK Source: https://docs.stagehand.dev/v3/configuration/models Install the Vercel AI SDK for Amazon Bedrock using npm, pnpm, yarn, or bun. ```bash npm install @ai-sdk/amazon-bedrock ``` ```bash pnpm add @ai-sdk/amazon-bedrock ``` ```bash yarn add @ai-sdk/amazon-bedrock ``` ```bash bun add @ai-sdk/amazon-bedrock ``` -------------------------------- ### Stagehand Agent First Run Exploration Example Source: https://docs.stagehand.dev/best-practices/deterministic-agent This example demonstrates the first run of an agent workflow with caching enabled. It measures the time taken for the agent to explore and execute actions using LLM inference. ```typescript import { Stagehand } from "@browserbasehq/stagehand"; const stagehand = new Stagehand({ env: "BROWSERBASE", cacheDir: "cache/github-search" // Enable caching }); await stagehand.init(); const page = stagehand.context.pages()[0]; await page.goto("https://github.com"); const agent = stagehand.agent({ mode: "cua", model: "google/gemini-3-flash-preview", systemPrompt: "You are a helpful assistant that can use a web browser.", }); console.log("First run: Exploring with agent..."); const startTime = Date.now(); const result = await agent.execute({ instruction: "Search for 'stagehand' and click the first repository result", maxSteps: 10 }); const duration = Date.now() - startTime; console.log(`First run completed in ${duration}ms`); console.log(`Actions: ${result.actions.length}`); console.log(`Status: ${result.success}`); await stagehand.close(); // Output (example): // First run completed in 25000ms // Actions: 8 // Status: true ``` -------------------------------- ### LLM Inference Call File Example Source: https://docs.stagehand.dev/configuration/logging Example structure of a 'Call File' which contains the complete LLM request, including the model call and messages. ```json { "modelCall": "act", "messages": [ { "role": "system", "content": "You are a browser automation assistant. You have access to these actions:\n- click\n- type\n- scroll\n..." }, { "role": "user", "content": "Click the sign in button\n\nDOM:\n\n \n \n \n \n" } ] } ``` -------------------------------- ### Example: Inject Script to Handle Dialogs Source: https://docs.stagehand.dev/v3/references/context An example demonstrating how to inject a script into the browser context to automatically handle alert, confirm, and prompt dialogs. ```typescript import { Stagehand } from "@browserbasehq/stagehand"; const stagehand = new Stagehand({ env: "LOCAL" }); await stagehand.init(); const context = stagehand.context; // Add some JavaScript to automatically accept alert dialogs await context.addInitScript(() => { window.alert = () => {}; window.confirm = () => true; window.prompt = () => ''; }); ``` -------------------------------- ### Hop Notation Examples Source: https://docs.stagehand.dev/v3/references/deeplocator Illustrates how to use hop notation (>>) for traversing multiple iframes. ```APIDOC ## PUT /api/users/{id} ### Description Updates an existing user's information. ### Method PUT ### Endpoint /api/users/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the user to update. #### Request Body - **email** (string) - Optional - The new email address for the user. ### Request Example { "email": "john.doe.updated@example.com" } ### Response #### Success Response (200) - **id** (string) - The unique identifier for the updated user. - **username** (string) - The username of the updated user. - **email** (string) - The updated email address of the user. #### Response Example { "id": "user-123", "username": "johndoe", "email": "john.doe.updated@example.com" } ``` -------------------------------- ### Successful Action Log Example Source: https://docs.stagehand.dev/v3/configuration/logging Example of a log entry for a successfully completed action. Includes auxiliary data like the selector and execution time. ```json { "category": "action", "message": "act completed successfully", "level": 1, "timestamp": "2025-01-27T12:35:00.123Z", "auxiliary": { "selector": { "value": "#btn-submit", "type": "string" }, "executionTime": { "value": "1250", "type": "integer" } } } ``` -------------------------------- ### Usage Patterns Source: https://docs.stagehand.dev/v3/references/response Examples demonstrating common usage patterns for navigation and response handling. ```APIDOC ## Usage Patterns ### Inspect status and headers ```typescript const response = await page.goto("https://httpbin.org/headers"); if (response) { console.log(response.status(), response.statusText()); const headers = await response.headersArray(); headers.forEach(({ name, value }) => { console.log(`${name}: ${value}`); }); } ``` ### Handle non-network navigations ```typescript const result = await page.goto("data:text/html,

inline

"); if (result === null) { console.log("No network response (data URL)"); } else { // Process as usual } ``` ### Await completion ```typescript const response = await page.goto("https://example.com/slow"); if (response) { const finished = await response.finished(); if (finished instanceof Error) { console.error("Navigation failed", finished.message); } } ``` ``` -------------------------------- ### Install Stagehand with yarn Source: https://docs.stagehand.dev/v3/first-steps/installation Use this command to add the Stagehand SDK to your project using yarn. ```bash yarn add @browserbasehq/stagehand ``` -------------------------------- ### Get Installed Python SDK Version Source: https://docs.stagehand.dev/v3/sdk/python Use this snippet to check the currently installed version of the Stagehand Python SDK. This is useful for troubleshooting or verifying upgrades. ```python import stagehand print(stagehand.__version__) ``` -------------------------------- ### Install Stagehand with pnpm Source: https://docs.stagehand.dev/v3/first-steps/installation Use this command to add the Stagehand SDK to your project using pnpm. ```bash pnpm add @browserbasehq/stagehand ``` -------------------------------- ### Checking Element States Source: https://docs.stagehand.dev/v3/references/locator Provides examples for checking element visibility, checkbox states, retrieving input values, and getting text content. Assumes relevant locators are defined. ```typescript // Check visibility const modal = page.locator(".modal"); if (await modal.isVisible()) { console.log("Modal is visible"); } // Check checkbox state const checkbox = page.locator("input#subscribe"); const checked = await checkbox.isChecked(); console.log("Subscribed:", checked); // Get input value const email = page.locator("input#email"); const value = await email.inputValue(); console.log("Email:", value); // Get text content const heading = page.locator("h1"); const text = await heading.textContent(); console.log("Heading:", text); ``` -------------------------------- ### Install Stagehand with npm Source: https://docs.stagehand.dev/v3/first-steps/installation Use this command to add the Stagehand SDK to your project using npm. ```bash npm install @browserbasehq/stagehand ``` -------------------------------- ### Example of Agent Execution Without Pre-Navigation (to avoid) Source: https://docs.stagehand.dev/basics/agent Shows an agent execution call without prior navigation to a page. This approach is less reliable as the agent may not start in the correct context. ```typescript await agent.execute('Go to GitHub and find the latest PR on browserbase/stagehand'); ``` -------------------------------- ### Quick Start with Google Gemini Source: https://docs.stagehand.dev/configuration/models Initialize Stagehand with Google Gemini using Model Gateway. The API key is automatically loaded from the GOOGLE_GENERATIVE_AI_API_KEY environment variable in your .env file. This setup is recommended for speed and cost-effectiveness. ```typescript import { Stagehand } from "@browserbasehq/stagehand"; const stagehand = new Stagehand({ env: "BROWSERBASE", model: "google/gemini-2.5-flash" // API key auto-loads from GOOGLE_GENERATIVE_AI_API_KEY - set in your .env }); await stagehand.init(); ``` -------------------------------- ### start Source: https://docs.stagehand.dev/v3/integrations/mcp/tools Create a new Browserbase session, or attach to an existing Browserbase session, and set it as active for the current MCP transport session. ```APIDOC ## start ### Description Create a new Browserbase session, or attach to an existing Browserbase session, and set it as active for the current MCP transport session. ### Parameters #### Query Parameters - **sessionId** (string) - Optional - Browserbase session ID to attach to. If omitted, `start` creates a new Browserbase session. ### Response #### Success Response (200) - **sessionId** (string) - Browserbase session ID now active for the current MCP transport session. ``` -------------------------------- ### Install CrewAI and Stagehand Source: https://docs.stagehand.dev/integrations/crew-ai/configuration Install the necessary Python packages for CrewAI and Stagehand integration. ```bash pip install stagehand crewai crewai-tools ``` -------------------------------- ### Run Next.js Development Server with npm Source: https://docs.stagehand.dev/integrations/vercel/configuration Start the Next.js development server using npm. ```bash npm run dev ``` -------------------------------- ### New SDK: Complete Migration Example Source: https://docs.stagehand.dev/v3/migrations/python Demonstrates a full web automation workflow using the newer Stagehand SDK, showing client initialization, session management, and integration with Playwright for navigation and actions. ```python import os import logging from dotenv import load_dotenv from playwright.sync_api import sync_playwright from stagehand import Stagehand # Standard Python logging (custom Stagehand logging not yet supported) logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) load_dotenv() SDK_VERSION = "3.0.6" def main(): # Create Stagehand API client client = Stagehand( browserbase_api_key=os.environ.get("BROWSERBASE_API_KEY"), model_api_key=os.environ.get("MODEL_API_KEY"), ) # Start a session start_response = client.sessions.start( model_name="google/gemini-2.0-flash", x_language="python", x_sdk_version=SDK_VERSION, ) session_id = start_response.data.session_id logger.info(f"Session started: {session_id}") logger.info(f"View live: https://www.browserbase.com/sessions/{session_id}") # Connect Playwright to the Browserbase session with sync_playwright() as playwright: browser = playwright.chromium.connect_over_cdp( f"wss://connect.browserbase.com?apiKey={os.environ['BROWSERBASE_API_KEY']}&sessionId={session_id}" ) context = browser.contexts[0] page = context.pages[0] if context.pages else context.new_page() try: # Navigate (using Playwright directly) page.goto("https://google.com/") logger.info("Navigated to Google") # Direct Playwright interaction page.get_by_role("link", name="About", exact=True).click() logger.info("Clicked About link") # Navigate back page.goto("https://google.com/") # AI-powered action (using Stagehand API) act_response = client.sessions.act( id=session_id, input="search for openai", x_language="python", x_sdk_version=SDK_VERSION, ) logger.info(f"Act completed: {act_response.data.result.message}") # Keyboard input (using Playwright) page.keyboard.press("Enter") # Wait for results page.wait_for_timeout(2000) # Observe elements (using Stagehand API) observe_response = client.sessions.observe( id=session_id, instruction="find all articles", x_language="python", x_sdk_version=SDK_VERSION, ) results = observe_response.data.result if results: element = results[0] logger.info(f"Found element: {element.description}") # Act on observed element client.sessions.act( id=session_id, input=element, x_language="python", x_sdk_version=SDK_VERSION, ) else: logger.warning("No elements found") # Extract data (using Stagehand API with schema) ``` -------------------------------- ### Full Stagehand Go SDK Workflow Example Source: https://docs.stagehand.dev/v3/sdk/go This snippet demonstrates the complete lifecycle of using the Stagehand Go SDK, including session management, navigation, interaction, data extraction, and agent execution. It requires setting Browserbase and Model API keys. ```go package main import ( "context" "fmt" "github.com/browserbase/stagehand-go" "github.com/browserbase/stagehand-go/option" ) func main() { // Create a new Stagehand client with your credentials client := stagehand.NewClient( option.WithBrowserbaseAPIKey("My Browserbase API Key"), // defaults to os.LookupEnv("BROWSERBASE_API_KEY") option.WithModelAPIKey("My Model API Key"), // defaults to os.LookupEnv("MODEL_API_KEY") ) // Start a new browser session startResponse, err := client.Sessions.Start(context.TODO(), stagehand.SessionStartParams{ ModelName: "gpt-5-nano", }) if err != nil { panic(err.Error()) } fmt.Printf("Session started: %s\n", startResponse.Data.SessionID) sessionID := startResponse.Data.SessionID // Navigate to a webpage _, err = client.Sessions.Navigate( context.TODO(), sessionID, stagehand.SessionNavigateParams{ URL: "https://news.ycombinator.com", }, ) if err != nil { panic(err.Error()) } fmt.Println("Navigated to Hacker News") // Use Observe to find possible actions on the page observeResponse, err := client.Sessions.Observe( context.TODO(), sessionID, stagehand.SessionObserveParams{ Instruction: stagehand.String("find the link to view comments for the top post"), }, ) if err != nil { panic(err.Error()) } actions := observeResponse.Data.Result fmt.Printf("Found %d possible actions\n", len(actions)) if len(actions) == 0 { fmt.Println("No actions found") return } // Take the first action returned by Observe action := actions[0] fmt.Printf("Acting on: %s\n", action.Description) // Pass the structured action to Act // The action contains selector, description, method, and arguments actResponse, err := client.Sessions.Act( context.TODO(), sessionID, stagehand.SessionActParams{ Input: stagehand.SessionActParamsInputUnion{ OfAction: &stagehand.ActionParam{ Description: action.Description, Selector: action.Selector, Method: stagehand.String(action.Method), Arguments: action.Arguments, }, }, }, ) if err != nil { panic(err.Error()) } fmt.Printf("Act completed: %s\n", actResponse.Data.Result.Message) // Extract structured data from the page using a JSON schema extractResponse, err := client.Sessions.Extract( context.TODO(), sessionID, stagehand.SessionExtractParams{ Instruction: stagehand.String("extract the text of the top comment"), Schema: map[string]any{ "type": "object", "properties": map[string]any{ "commentText": map[string]any{ "type": "string", "description": "The text content of the top comment", }, "author": map[string]any{ "type": "string", "description": "The username of the comment author", }, }, }, }, ) if err != nil { panic(err.Error()) } fmt.Printf("Extracted: %+v\n", extractResponse.Data.Result) // Run an autonomous agent to accomplish a goal // The agent can navigate, click, type, and interact with pages executeResponse, err := client.Sessions.Execute( context.TODO(), sessionID, stagehand.SessionExecuteParams{ ExecuteOptions: stagehand.SessionExecuteParamsExecuteOptions{ Instruction: "Find the profile page for the top commenter", MaxSteps: stagehand.Float(10), }, AgentConfig: stagehand.SessionExecuteParamsAgentConfig{ // Model config with provider/model format and API key Model: stagehand.ModelConfigUnionParam{ OfModelConfigModelConfigObject: &stagehand.ModelConfigModelConfigObjectParam{ ModelName: "openai/gpt-4.1-mini", APIKey: stagehand.String("sk-your-api-key"), }, }, Cua: stagehand.Bool(false), }, }, ) if err != nil { panic(err.Error()) } fmt.Printf("Agent result: %s\n", executeResponse.Data.Result.Message) // End the session to clean up resources _, err = client.Sessions.End( context.TODO(), sessionID, stagehand.SessionEndParams{}, ) if err != nil { panic(err.Error()) } fmt.Println("Session ended") } ``` -------------------------------- ### Create Project Structure Source: https://docs.stagehand.dev/v3/best-practices/deployments Creates the necessary directories and files for a Stagehand project on Vercel. ```bash mkdir -p api touch api/run.ts package.json vercel.json tsconfig.json ``` -------------------------------- ### Install Stagehand Dependencies with yarn Source: https://docs.stagehand.dev/integrations/vercel/configuration Install the necessary Stagehand and related dependencies using yarn. ```bash yarn add @browserbasehq/stagehand @browserbasehq/sdk playwright zod ``` -------------------------------- ### Old SDK: Complete Migration Example Source: https://docs.stagehand.dev/v3/migrations/python Illustrates a full web automation workflow using the older Stagehand SDK, including navigation, direct Playwright interaction, AI-powered actions, observation, and data extraction. ```python import asyncio import logging import os from dotenv import load_dotenv from stagehand import Stagehand, StagehandConfig, configure_logging configure_logging(level=logging.INFO, remove_logger_name=True, quiet_dependencies=True) load_dotenv() async def main(): config = StagehandConfig( env="BROWSERBASE", api_key=os.getenv("BROWSERBASE_API_KEY"), headless=False, model_name="google/gemini-2.0-flash", model_client_options={"apiKey": os.getenv("MODEL_API_KEY")}, verbose=2, ) stagehand = Stagehand(config) await stagehand.init() page = stagehand.page print(f"Session: {stagehand.session_id}") # Navigate await page.goto("https://google.com/") # Direct Playwright interaction await page.get_by_role("link", name="About", exact=True).click() # AI-powered action await page.goto("https://google.com/") await page.act("search for openai") await page.keyboard.press("Enter") # Observe and act observed = await page.observe("find all articles") if observed: await page.act(observed[0]) # Extract data data = await page.extract("extract the first result") print(data.model_dump_json()) await stagehand.close() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Install Stagehand Dependencies with pnpm Source: https://docs.stagehand.dev/integrations/vercel/configuration Install the necessary Stagehand and related dependencies using pnpm. ```bash pnpm add @browserbasehq/stagehand @browserbasehq/sdk playwright zod ``` -------------------------------- ### Full Stagehand Workflow Example Source: https://docs.stagehand.dev/v3/sdk/python Demonstrates the complete Stagehand workflow: session creation, navigation, observing actions, acting on elements, extracting data, and running an autonomous agent. Ensure BROWSERBASE_API_KEY and MODEL_API_KEY environment variables are set. ```python import asyncio from stagehand import AsyncStagehand async def main() -> None: # Create client using environment variables: # BROWSERBASE_API_KEY, MODEL_API_KEY client = AsyncStagehand() # Start a new browser session (returns a session helper bound to a session_id) session = await client.sessions.create(model_name="openai/gpt-5-nano") print(f"Session started: {session.id}") try: # Navigate to a webpage await session.navigate( url="https://news.ycombinator.com", ) print("Navigated to Hacker News") # Observe to find possible actions on the page observe_response = await session.observe( instruction="find the link to view comments for the top post", ) 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 = await session.act(input=action) print("Act completed:", act_response.data.result.message) # Extract structured data from the page using a JSON schema extract_response = await session.extract( instruction="extract the text of the top comment on this page", schema={ "type": "object", "properties": { "commentText": {"type": "string"}, "author": {"type": "string"}, }, "required": ["commentText"], }, ) 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 = await session.execute( 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"}, 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 await session.end() print("Session ended") if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Install Stagehand Dependencies with npm Source: https://docs.stagehand.dev/integrations/vercel/configuration Install the necessary Stagehand and related dependencies using npm. ```bash npm install @browserbasehq/stagehand @browserbasehq/sdk playwright zod ``` -------------------------------- ### End Browser Session Response Example Source: https://docs.stagehand.dev/v3/api-reference/go/end-a-browser-session This is an example of a successful response when ending a browser session. ```json { "success": true } ``` -------------------------------- ### Install Stagehand Gem Source: https://docs.stagehand.dev/v3/sdk/ruby Add the Stagehand gem to your application's Gemfile for installation via Bundler. ```ruby gem "stagehand", "~> 0.6.2" ``` -------------------------------- ### Configure Client with Mixed Approaches Source: https://docs.stagehand.dev/v3/sdk/java Combine environment variable configuration with manual settings. System properties and environment variables take precedence over manually set values if they exist. ```java import com.browserbase.api.client.StagehandClient; import com.browserbase.api.client.okhttp.StagehandOkHttpClient; StagehandClient client = StagehandOkHttpClient.builder() // Configures using the `stagehand.browserbaseApiKey`, `stagehand.modelApiKey` and `stagehand.baseUrl` system properties // Or configures using the `BROWSERBASE_API_KEY`, `MODEL_API_KEY` and `STAGEHAND_API_URL` environment variables .fromEnv() .browserbaseApiKey("My Browserbase API Key") .build(); ``` -------------------------------- ### Install Stagehand and Puppeteer Source: https://docs.stagehand.dev/v3/integrations/puppeteer Install the necessary packages for Stagehand and Puppeteer. This is a prerequisite for integrating the two libraries. ```bash npm install @browserbasehq/stagehand puppeteer-core ``` -------------------------------- ### Install Convex Stagehand and Zod Source: https://docs.stagehand.dev/v3/integrations/convex/configuration Install the necessary npm packages for Stagehand and Zod schema validation. ```bash npm install @browserbasehq/convex-stagehand zod ``` -------------------------------- ### Configure Client from Environment Variables Source: https://docs.stagehand.dev/v3/sdk/java Configure the client using environment variables for API keys and base URL. Ensure the relevant environment variables are set before initializing the client. ```java import com.browserbase.api.client.StagehandClient; import com.browserbase.api.client.okhttp.StagehandOkHttpClient; // Configures using the `stagehand.browserbaseApiKey`, `stagehand.modelApiKey` and `stagehand.baseUrl` system properties // Or configures using the `BROWSERBASE_API_KEY`, `MODEL_API_KEY` and `STAGEHAND_API_URL` environment variables StagehandClient client = StagehandOkHttpClient.fromEnv(); ``` -------------------------------- ### Run Next.js Development Server with pnpm Source: https://docs.stagehand.dev/integrations/vercel/configuration Start the Next.js development server using pnpm. ```bash pnpm dev ``` -------------------------------- ### Configure Environment Variables Source: https://docs.stagehand.dev/integrations/crew-ai/configuration Set up environment variables for Browserbase and LLM API keys. Ensure these keys are obtained from their respective dashboards. ```bash BROWSERBASE_API_KEY="your-browserbase-api-key" OPENAI_API_KEY="your-openai-api-key" ANTHROPIC_API_KEY="your-anthropic-api-key" ``` -------------------------------- ### Basic Local Stagehand Setup Source: https://docs.stagehand.dev/configuration/browser Initializes Stagehand for a local environment. This is the most basic setup for local development. ```javascript import { Stagehand } from "@browserbasehq/stagehand"; const stagehand = new Stagehand({ env: "LOCAL" }); await stagehand.init(); console.log("Session ID:", stagehand.sessionId); ``` -------------------------------- ### Configuring Client and Request Options in Go Source: https://docs.stagehand.dev/v3/sdk/go Illustrates the use of the functional options pattern in the Go SDK for configuring clients and individual requests. Options like `WithHeader` and `WithJSONSet` allow for customization of request behavior. ```go client := stagehand.NewClient( // Adds a header to every request made by the client option.WithHeader("X-Some-Header", "custom_header_info"), ) client.Sessions.Start(context.TODO(), ..., // Override the header option.WithHeader("X-Some-Header", "some_other_custom_header_info"), // Add an undocumented field to the request body, using sjson syntax option.WithJSONSet("some.json.path", map[string]string{"my": "object"}), ) ``` -------------------------------- ### Async Session Initialization and Closing (v2) Source: https://docs.stagehand.dev/v3/migrations/python Example of initializing and closing a Stagehand session asynchronously using the older SDK (v2). This pattern is suitable for async applications. ```python async def main(): stagehand = Stagehand(config) await stagehand.init() await page.goto("https://example.com") await stagehand.close() asyncio.run(main()) ``` -------------------------------- ### Install Go Dependencies Source: https://docs.stagehand.dev/v3/sdk/go Run `go mod tidy` to download and manage the necessary dependencies for the Stagehand Go SDK. ```bash go mod tidy ``` -------------------------------- ### Configure Custom Host and Port Source: https://docs.stagehand.dev/v3/integrations/mcp/configuration Configure custom host and port for SHTTP transport. This example also shows how to set API keys for both Browserbase and Gemini. ```json { "mcpServers": { "browserbase": { "command": "npx", "args": [ "@browserbasehq/mcp", "--host", "0.0.0.0", "--port", "8080" ], "env": { "BROWSERBASE_API_KEY": "your_api_key", "GEMINI_API_KEY": "your_gemini_api_key" } } } } ``` -------------------------------- ### Action Response Example Source: https://docs.stagehand.dev/v3/api-reference/ruby/perform-an-action This is an example of a successful response when performing an action. It includes details about the action taken and its outcome. ```json { "success": true, "data": { "result": { "success": true, "message": "Successfully clicked the login button", "actionDescription": "Clicked button with text 'Login'", "actions": [ { "selector": "[data-testid='submit-button']", "description": "Click the submit button", "backendNodeId": 123, "method": "click", "arguments": [ "Hello World" ] } ] }, "actionId": "" } } ``` -------------------------------- ### Set Environment Variables for Credentials Source: https://docs.stagehand.dev/v3/sdk/ruby Before running the example script, set your Browserbase and OpenAI API keys as environment variables. ```bash # Set your credentials export BROWSERBASE_API_KEY="your-browserbase-api-key" export MODEL_API_KEY="your-openai-api-key" ``` -------------------------------- ### Create Browserbase Session with SDK Source: https://docs.stagehand.dev/v3/configuration/browser Initialize the Browserbase SDK and create a new session. Add configuration options within the session creation object as needed. ```typescript import { Browserbase } from "@browserbasehq/sdk"; const bb = new Browserbase({ apiKey: process.env.BROWSERBASE_API_KEY! }); const session = await bb.sessions.create({ // Add configuration options here }); ``` -------------------------------- ### Install dotenv for .env file support Source: https://docs.stagehand.dev/v3/first-steps/installation If you are using a .env file to manage environment variables, install the dotenv package. ```bash npm install dotenv ``` -------------------------------- ### Configure Agent with Custom Model and System Prompt Source: https://docs.stagehand.dev/v3/references/agent Shows how to create an agent with a specific model, a custom system prompt for guiding behavior, and a different model for execution. This allows for fine-tuning the agent's responses and actions. ```typescript // Create agent with custom model and system prompt const agent = stagehand.agent({ model: "openai/computer-use-preview", systemPrompt: "You are a helpful assistant that can navigate websites efficiently. Always verify actions before proceeding.", executionModel: "openai/gpt-4o-mini" // Use faster model for tool execution }); const page = stagehand.context.pages()[0]; await page.goto("https://example.com"); const result = await agent.execute({ instruction: "Fill out the contact form with test data", maxSteps: 10, highlightCursor: true }); ``` -------------------------------- ### Install Browserbase MCP with Claude CLI Source: https://docs.stagehand.dev/v3/integrations/mcp/setup Use this command to add Browserbase MCP to your Claude Code environment for one-click installation. ```bash claude mcp add --transport http browserbase "https://mcp.browserbase.com/mcp?browserbaseApiKey=YOUR_BROWSERBASE_API_KEY" ```