> ## Documentation Index
> Fetch the complete documentation index at: https://docs.stagehand.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# LangChain JS Configuration

> Set up Stagehand with LangChain JS to create intelligent web automation agents

export const V3Banner = () => null;

<V3Banner />

This guide walks you through integrating Stagehand with LangChain JS to build powerful web automation workflows using natural language instructions.

## Step 1: Install Dependencies

Install the required packages for LangChain JS and Stagehand integration:

```bash theme={null}
npm install @langchain/langgraph @langchain/community @langchain/core @browserbasehq/stagehand
```

## Step 2: Configure Environment Variables

For remote browser automation, set up your Browserbase credentials:

```bash theme={null}
BROWSERBASE_API_KEY="your-browserbase-api-key"
```

## Step 3: Create a Stagehand Instance

Initialize Stagehand with your preferred configuration:

```typescript theme={null}
import { Stagehand } from "@browserbasehq/stagehand";

// For local development
const stagehand = new Stagehand({
    env: "LOCAL",
    verbose: 2,
    enableCaching: false,
});

// For production with Browserbase
const stagehand = new Stagehand({
    env: "BROWSERBASE",
    verbose: 1,
    enableCaching: true,
});
```

## Step 4: Generate the StagehandToolkit

Create the toolkit that provides LangChain-compatible tools:

```typescript theme={null}
import { StagehandToolkit } from '@langchain/community/agents/toolkits/stagehand';

const stagehandToolkit = await StagehandToolkit.fromStagehand(stagehand);
```

## Step 5: Use Individual Tools

The toolkit provides four specialized tools for web automation:

### Available Tools

* **stagehand\_navigate**: Navigate to specific URLs
* **stagehand\_act**: Perform browser actions (clicking, typing, etc.)
* **stagehand\_extract**: Extract structured data using schemas
* **stagehand\_observe**: Analyze page elements and possible actions

### Basic Tool Usage

```typescript theme={null}
import { z } from "zod";

// Navigate to a website
const navigateTool = stagehandToolkit.tools.find(
    (t) => t.name === "stagehand_navigate"
);
await navigateTool.invoke("https://www.google.com");

// Perform an action
const actionTool = stagehandToolkit.tools.find(
    (t) => t.name === "stagehand_act"
);
await actionTool.invoke('Search for "OpenAI"');

// Observe the page
const observeTool = stagehandToolkit.tools.find(
    (t) => t.name === "stagehand_observe"
);
const result = await observeTool.invoke(
    "What actions can be performed on the current page?"
);
console.log(JSON.parse(result));

// Extract structured data
const extractTool = stagehandToolkit.tools.find(
    (t) => t.name === "stagehand_extract"
);
const extractResult = await extractTool.invoke({
    instruction: "Extract the main heading and description",
    schema: z.object({
        heading: z.string(),
        description: z.string(),
    }),
});
console.log(extractResult);
```

## Step 6: Build LangGraph Agents

Integrate with LangGraph for complex automation workflows:

```typescript theme={null}
import { createReactAgent } from "@langchain/langgraph/prebuilt";

// Create an LLM
const llm = new ChatOpenAI({
    model: "gpt-4",
    temperature: 0,
});

// Create an agent with Stagehand tools
const agent = createReactAgent({
    llm,
    tools: stagehandToolkit.tools,
});

// Execute a complex workflow
const result = await agent.invoke({
    messages: [
        {
            role: "user", 
            content: "Go to example.com, find the contact form, and extract all the form fields"
        }
    ]
});
```

## Advanced Configuration

### Custom Stagehand Configuration

```typescript theme={null}
const stagehand = new Stagehand({
    env: "BROWSERBASE",
    verbose: 2,
    enableCaching: true,
    headless: true,
    domSettleTimeoutMs: 5000,
});
```

### Error Handling

```typescript theme={null}
try {
    const result = await agent.invoke({
        messages: [{ role: "user", content: "Navigate to invalid-url.com" }]
    });
} catch (error) {
    console.error("Automation failed:", error);
} finally {
    // Clean up resources
    await stagehand.close();
}
```

## Example Workflows

<Tabs>
  <Tab title="Data Extraction" value="data-extraction" label="TypeScript">
    ```typescript theme={null}
    const extractionAgent = createReactAgent({
        llm,
        tools: stagehandToolkit.tools,
    });

    const result = await extractionAgent.invoke({
        messages: [{
            role: "user",
            content: `
                Go to news-website.com and extract:
                1. All article headlines
                2. Publication dates  
                3. Author names
                Format as structured JSON
            `
        }]
    });
    ```
  </Tab>

  <Tab title="Form Automation" value="form-automation" label="TypeScript">
    ```typescript theme={null}
    const formAgent = createReactAgent({
        llm,
        tools: stagehandToolkit.tools,
    });

    const result = await formAgent.invoke({
        messages: [{
            role: "user", 
            content: `
                Navigate to contact-form.com and:
                1. Fill out the contact form with:
                   - Name: John Doe
                   - Email: john@example.com
                   - Message: Inquiry about services
                2. Submit the form
                3. Confirm submission success
            `
        }]
    });
    ```
  </Tab>

  <Tab title="Multi-site Research" value="multi-site-research" label="TypeScript">
    ```typescript theme={null}
    const researchAgent = createReactAgent({
        llm,
        tools: stagehandToolkit.tools,
    });

    const result = await researchAgent.invoke({
        messages: [{
            role: "user",
            content: `
                Research product pricing by:
                1. Visit competitor1.com and extract pricing info
                2. Visit competitor2.com and extract pricing info  
                3. Compare features and prices
                4. Provide summary analysis
            `
        }]
    });
    ```
  </Tab>
</Tabs>

<CardGroup cols={1}>
  <Card title="LangChain JS Documentation" icon="book" href="https://js.langchain.com/docs/integrations/tools/stagehand/">
    Official LangChain JS documentation for the Stagehand integration
  </Card>
</CardGroup>
