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

# Langchain JS

> 将 Stagehand 与 Langchain JS 集成

通过使用 `StagehandToolkit` 封装 Stagehand 的浏览器自动化功能，可以将其集成到 Langchain JS 中。

该工具包提供了一系列专用工具，包括 `navigate`、`act`、`extract` 和 `observe`，均由 Stagehand 的底层能力驱动。

有关此集成及如何与 Langchain 协作的更多详情，请参阅 [Langchain 官方文档](https://js.langchain.com/docs/integrations/tools/stagehand/)。

以下是入门的高级概述：

## 安装

安装必要的软件包：

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

## 创建 Stagehand 实例

```typescript theme={null}
const stagehand = new Stagehand({
	env: "LOCAL",
	verbose: 2,
	enableCaching: false,
});
```

## 生成 Stagehand 工具包对象

```typescript theme={null}
const stagehandToolkit = await StagehandToolkit.fromStagehand(stagehand);
```

## 使用工具

* `stagehand_navigate`：导航至特定 URL。
* `stagehand_act`：执行浏览器自动化任务，如点击按钮和在字段中输入内容。
* `stagehand_extract`：使用 Zod 模式从页面提取结构化数据。
* `stagehand_observe`：检查 DOM 以寻找可能的操作或相关元素。

独立使用示例：

```typescript theme={null}
// Find the relevant tool
const navigateTool = stagehandToolkit.tools.find(
(t) => t.name === "stagehand_navigate");

// Invoke it
await navigateTool.invoke("https://www.google.com");

// Suppose you want to act on the page
const actionTool = stagehandToolkit.tools.find(
(t) => t.name === "stagehand_act");

await actionTool.invoke('Search for "OpenAI"');

// Observe the current 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));

// Verification
const currentUrl = stagehand.page.url();
// e.g., ensure it contains "google.com/search"
```

## 远程浏览器（Browserbase）

无需指定 env: "LOCAL"，而是指定 env: "BROWSERBASE" 并通过环境变量传入 Browserbase 凭据：
`BROWSERBASE_API_KEY`、`BROWSERBASE_PROJECT_ID`

## 使用 LangGraph 代理

`StagehandToolkit` 也可以接入 LangGraph 现有的代理系统。通过将 Stagehand 的工具与其他 Langchain 工具结合使用，您可以编排更复杂的工作流。

借助 `StagehandToolkit`，您可以快速将自然语言驱动的浏览器自动化集成到 Langchain 支持的工作流中。这支持以下用例：

* 从网站搜索、提取和汇总数据
* 自动化登录流程
* 根据更复杂的代理链指令导航或点击表单

如需故障排除和高级集成，请查阅 Stagehand 和 Langchain 的官方参考文档，或通过 [Slack](https://stagehand.dev/slack) 联系我们。
