# @browserbasehq/convex-stagehand 中文文档

规范地址：https://npmcn.com/package/%40browserbasehq/convex-stagehand/

版本：0\.1\.1
npm 元数据更新时间：2026-08-31T16:40:56.372Z
中文译文更新时间：2026-11-08T16:22:09.820Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40browserbasehq/convex-stagehand
原文对照：https://npmcn.com/package/%40browserbasehq/convex-stagehand/?lang=original
项目主页：https://github.com/browserbase/integrations#readme
源码仓库：https://github.com/browserbase/integrations

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：246 kB，55 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- 运行依赖：1 个
- peer 依赖：zod ^3\.23\.0，convex ^1\.29\.3
- 首次发布：2026-01-27T09:50:16.601Z
- 最新版本发布：2026-05-20T23:03:02.268Z
- 近 30 天下载量：9604（2026-10-09 至 2026-11-07，npm 官方下载统计）
- 已发布版本数：5（近 12 个月 5 个）

## 中文简介

用 Stagehand 实现 AI 驱动浏览器自动化的对流组件

## 安装

```sh
npm install @browserbasehq/convex-stagehand
```

也可以使用：`pnpm add @browserbasehq/convex-stagehand`、`yarn add @browserbasehq/convex-stagehand`、`bun add @browserbasehq/convex-stagehand`

## README

# 对流相控手

Convex应用程序的AI-动力浏览器自动化. 提取数据,执行动作,并使用自然语言实现工作流程自动化 - 不需要Playwright知识.

## 特征

-   **简单 API** - 用简单的英语描述你想要什么
-   **类型安全** - 用Zod schemas提供全部类型脚本支持
-   **会话管理** - 在多个操作中重复使用浏览器会话
-   **代理模式** - 自动多步骤任务执行
-   **由 Stagehand 提供动力** - 使用 [阶段手](https://github.com/browserbase/stagehand) (原始内容存档于2013-10-12) (英语). REST API

## 快速启动

### 1\. 安装组件

```bash
npm install @browserbasehq/convex-stagehand zod
```

### 2\. 配置对流

将组件添加到您的 `convex/convex.config.ts`数字 :

```typescript
import { defineApp } from "convex/server";
import stagehand from "convex-stagehand/convex.config";

const app = defineApp();
app.use(stagehand, { name: "stagehand" });

export default app;
```

### 3\. 设置环境变量

把这些添加到您的 [凸起板](https://dashboard.convex.dev/) 环境变量:

| 变量 | 说明 |
| --- | --- |
| `BROWSERBASE_API_KEY` | 您的浏览器库 API 密钥 |
| `BROWSERBASE_PROJECT_ID` | 您的浏览器项目 ID |
| `MODEL_API_KEY` | 您的 LLM 提供者 API 密钥( OpenAI, Anthropic等) |

### 4\. 使用该构成部分

```typescript
import { action } from "./_generated/server";
import { Stagehand } from "convex-stagehand";
import { components } from "./_generated/api";
import { z } from "zod";

const stagehand = new Stagehand(components.stagehand, {
  browserbaseApiKey: process.env.BROWSERBASE_API_KEY!,
  browserbaseProjectId: process.env.BROWSERBASE_PROJECT_ID!,
  modelApiKey: process.env.MODEL_API_KEY!,
});

export const scrapeHackerNews = action({
  handler: async (ctx) => {
    return await stagehand.extract(ctx, {
      url: "https://news.ycombinator.com",
      instruction: "Extract the top 5 stories with title, score, and link",
      schema: z.object({
        stories: z.array(z.object({
          title: z.string(),
          score: z.string(),
          link: z.string(),
        }))
      })
    });
  }
});
```

## API 参考

### `startSession(ctx, args)`

启动一个新的浏览器会话 。 返回会话信息,用于其他操作.

```typescript
const session = await stagehand.startSession(ctx, {
  url: "https://example.com",
  browserbaseSessionID: "optional-existing-session-id",
  options: {
    timeout: 30000,
    waitUntil: "networkidle",
    domSettleTimeoutMs: 2000,
    selfHeal: true,
    systemPrompt: "Custom system prompt for the session",
  }
});
// { sessionId: "...", cdpUrl: "wss://..." }
```

**参数:**

-   `url` - 要导航的 URL
-   `browserbaseSessionID` - 可选:恢复现有的浏览器会话
-   `options.timeout` - 导航超时(以毫秒计)
-   `options.waitUntil` - 何时考虑完成导航: `"load"`, (中文(简体) ), `"domcontentloaded"`,或 `"networkidle"`
-   `options.domSettleTimeoutMs` - DOM 在考虑加载页面前结算的超时
-   `options.selfHeal` - 启用自愈能力,使自动化更加健全
-   `options.systemPrompt` - 自定义系统在会话中提示AI的行为

**回返情况:**

```typescript
{
  sessionId: string; // Use with other operations
  cdpUrl?: string;   // For advanced Playwright/Puppeteer usage
}
```

* * *

### `endSession(ctx, args)`

结束浏览器会话 .

```typescript
await stagehand.endSession(ctx, { sessionId: session.sessionId });
```

**参数:**

-   `sessionId` - 会议结束

**回返情况:** `{ success: boolean }`

* * *

### `extract(ctx, args)`

从使用AI的网页中提取结构化数据.

```typescript
// Without session (creates and destroys its own)
const data = await stagehand.extract(ctx, {
  url: "https://example.com",
  instruction: "Extract all product names and prices",
  schema: z.object({
    products: z.array(z.object({
      name: z.string(),
      price: z.string(),
    }))
  }),
});

// With existing session (reuses session, doesn't end it)
const data = await stagehand.extract(ctx, {
  sessionId: session.sessionId,
  instruction: "Extract all product names and prices",
  schema: z.object({ ... }),
});
```

**参数:**

-   `sessionId` - 可选:利用现有会话
-   `url` - 要导航的 URL( 如果没有会话需要的话) (d) 国家
-   `instruction` - 如何提取的自然语言描述
-   `schema` - 确定预期产出结构的Zod计划
-   `options.timeout` - 导航超时(以毫秒计)
-   `options.waitUntil` - 何时考虑完成导航: `"load"`, (中文(简体) ), `"domcontentloaded"`,或 `"networkidle"`

**回返情况:** 匹配您的 Zod 方案的数据

* * *

### `act(ctx, args)`

使用自然语言执行浏览器动作 .

```typescript
// Without session
const result = await stagehand.act(ctx, {
  url: "https://example.com/login",
  action: "Click the login button and wait for the page to load",
});

// With existing session
const result = await stagehand.act(ctx, {
  sessionId: session.sessionId,
  action: "Fill in the email field with 'user@example.com'",
});
```

**参数:**

-   `sessionId` - 可选:利用现有会话
-   `url` - 要导航的 URL( 如果没有会话需要的话) (d) 国家
-   `action` - 执行行动的自然语言描述
-   `options.timeout` - 导航超时(以毫秒计)
-   `options.waitUntil` - 何时考虑完成导航

**回返情况:**

```typescript
{
  success: boolean;
  message: string;
  actionDescription: string;
}
```

* * *

### `observe(ctx, args)`

在网页上查找可用的动作 .

```typescript
const actions = await stagehand.observe(ctx, {
  url: "https://example.com",
  instruction: "Find all clickable navigation links",
});
// [{ description: "Home link", selector: "a.nav-home", method: "click" }, ...]
```

**参数:**

-   `sessionId` - 可选:利用现有会话
-   `url` - 要导航的 URL( 如果没有会话需要的话) (d) 国家
-   `instruction` - 自然语言描述需要找到什么行动
-   `options.timeout` - 导航超时(以毫秒计)
-   `options.waitUntil` - 何时考虑完成导航

**回返情况:**

```typescript
Array<{
  description: string;
  selector: string;
  method: string;
  arguments?: string[];
}>
```

* * *

### `agent(ctx, args)`

使用AI代理执行自动多步浏览器自动化. 代理人解释指令,决定要采取的行动.

```typescript
// Agent creates its own session
const result = await stagehand.agent(ctx, {
  url: "https://google.com",
  instruction: "Search for 'convex database' and extract the top 3 results with title and URL",
  options: { maxSteps: 10 },
});

// Agent with existing session
const result = await stagehand.agent(ctx, {
  sessionId: session.sessionId,
  instruction: "Fill out the contact form and submit",
  options: { maxSteps: 5 },
});
```

**参数:**

-   `sessionId` - 可选:利用现有会话
-   `url` - 要导航的 URL( 如果没有会话需要的话) (d) 国家
-   `instruction` - 完成任务的自然语言描述
-   `options.cua` - 启用计算机使用代理模式
-   `options.maxSteps` - 特工可以采取的最大步骤
-   `options.systemPrompt` - 代理人自定义系统提示
-   `options.timeout` - 导航超时(以毫秒计)
-   `options.waitUntil` - 何时考虑完成导航

**回返情况:**

```typescript
{
  actions: Array<{
    type: string;
    action?: string;
    reasoning?: string;
    timeMs?: number;
  }>;
  completed: boolean;
  message: string;
  success: boolean;
}
```

## 实例

### 简单提取( 自动会话)

```typescript
const news = await stagehand.extract(ctx, {
  url: "https://news.ycombinator.com",
  instruction: "Get the top 10 stories with title, points, and comment count",
  schema: z.object({
    stories: z.array(z.object({
      title: z.string(),
      points: z.string(),
      comments: z.string(),
    }))
  })
});
```

### 人工会话管理

当您需要执行多个操作时, 请使用会话管理

```typescript
// Start a session
const session = await stagehand.startSession(ctx, {
  url: "https://google.com"
});

// Perform multiple operations in the same session
await stagehand.act(ctx, {
  sessionId: session.sessionId,
  action: "Search for 'convex database'"
});

const data = await stagehand.extract(ctx, {
  sessionId: session.sessionId,
  instruction: "Extract the top 3 results",
  schema: z.object({
    results: z.array(z.object({
      title: z.string(),
      url: z.string(),
    }))
  })
});

// End the session when done
await stagehand.endSession(ctx, { sessionId: session.sessionId });
```

### 自动代理

让AI代理商找出如何完成一项复杂的任务:

```typescript
const result = await stagehand.agent(ctx, {
  url: "https://www.google.com",
  instruction: "Search for 'best pizza in NYC', click on the first result, and extract the restaurant name and address",
  options: { maxSteps: 10 }
});

console.log(result.message); // Summary of what the agent did
console.log(result.actions); // Detailed log of each action taken
```

### Convex 行动中恢复会话

存储 `sessionId` 继续用同样的Stagehand会话在不同的Convex动作中工作,呼吁:

```typescript
// Action 1: Start session and return sessionId
export const startBrowsing = action({
  handler: async (ctx) => {
    const session = await stagehand.startSession(ctx, {
      url: "https://example.com/login"
    });
    // Store sessionId in your database
    return session.sessionId;
  }
});

// Action 2: Continue same session later
export const continueBrowsing = action({
  args: { sessionId: v.string() },
  handler: async (ctx, args) => {
    await stagehand.act(ctx, {
      sessionId: args.sessionId,
      action: "Navigate to the dashboard page",
    });

    return await stagehand.extract(ctx, {
      sessionId: args.sessionId,
      instruction: "Extract user data",
      schema: z.object({ ... }),
    });
  }
});
```

## 配置选项

### AI 模型

默认情况下,组件使用 `openai/gpt-4o`中。您可以使用由 [维塞尔 AI SDK](https://sdk.vercel.ai/providers/ai-sdk-providers) 支持结构化产出:

```typescript
const stagehand = new Stagehand(components.stagehand, {
  browserbaseApiKey: process.env.BROWSERBASE_API_KEY!,
  browserbaseProjectId: process.env.BROWSERBASE_PROJECT_ID!,
  modelApiKey: process.env.ANTHROPIC_API_KEY!, // Use Anthropic
  modelName: "anthropic/claude-3-5-sonnet-20241022",
});
```

获得支持的模型和提供者的完整清单,见 [模型文档](https://docs.stagehand.dev/configuration/models)。 。 。 .

## 所需资源

-   [浏览器库](https://browserbase.com/) 账户和 API 密钥
-   LLM 提供者 API 密钥( 参见 [支持的模型](https://docs.stagehand.dev/configuration/models)(中文(简体) )
-   1.29.3或以后的对流

## 如何运作

此组件使用 [阶段手 REST API](https://stagehand.stldocs.app/api) 以启动浏览器自动化。 每个操作 :

1.  通过浏览器库启动云浏览器会话( 或重新使用已有的会话)
2.  导航到目标 URL
3.  使用AI来理解页面并进行请求操作
4.  可选结束会话并返回结果

通过会话管理,您控制会话开始和结束时,允许您在多个操作中保持浏览器状态.

## 发展

### 构成部分结构

该组件通过Convex组件系统来曝光其API. 所有函数都是在一个 `lib.ts` 模块 :

```
component.lib.<function>
```

例如:

-   `component.lib.startSession` - 启动浏览器会话
-   `component.lib.endSession` - 结束浏览器会话
-   `component.lib.extract` - 从网页提取数据
-   `component.lib.act` - 执行浏览器动作
-   `component.lib.observe` - 寻找互动要素
-   `component.lib.agent` - 自动多步自动化

这个 `Stagehand` 客户端类包装这些内部路径以提供干净的用户 API :

```typescript
// User calls:
stagehand.extract(ctx, {...})

// Internally calls:
ctx.runAction(component.lib.extract, {...})
```

### 建设构成部分

为在当地建立这一构成部分:

```bash
# Install dependencies
npm install

# Build with Convex codegen (generates component API)
npm run build:codegen

# Or just build TypeScript
npm run build:esm
```

该构成部分需要部署Convex,以产生适当的构成部分API类型(`_generated/component.ts`) (中文(简体) ).

### 示例应用

请检查url=值 (帮助) [`example/`](https://npmcn.com/package/%40browserbasehq/convex-stagehand/example) 目录 :

```bash
git clone https://github.com/browserbase/integrations
cd integrations/packages/convex-stagehand/example
npm install
npm run dev
```

例子包括:

-   HackerNews 与 AI 的故事提取
-   使用 Zod schemas 提取安全数据
-   带有 Convex 的数据库持久性
-   实时更新和自动刷新

## 许可证

麻省理工学院

## 常见问题

### @browserbasehq/convex-stagehand 是什么？

用 Stagehand 实现 AI 驱动浏览器自动化的对流组件

### 如何安装 @browserbasehq/convex-stagehand？

在项目目录运行 npm install @browserbasehq/convex-stagehand，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：zod（^3\.23\.0）、convex（^1\.29\.3）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @browserbasehq/convex-stagehand 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @browserbasehq/convex-stagehand 支持 ESM 还是 CommonJS？

以 ES Module 形式发布，推荐使用 import 引入。在 CommonJS 项目中，Node\.js 20\.19\+ / 22\.12\+ 可以直接 require\(\) 不含顶层 await 的 ES Module，更早的版本需要改用动态 import\(\)。

### @browserbasehq/convex-stagehand 可以商用吗？

@browserbasehq/convex-stagehand 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @browserbasehq/convex-stagehand 的下载量有多少？

根据 npm 官方下载统计，@browserbasehq/convex-stagehand 在 2026/10/09 – 2026/11/07 这 30 天内被下载 9,604 次，日均约 320 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @browserbasehq/convex-stagehand 还在维护吗？

最新版本 0\.1\.1 发布于 2026/05/21（5 个月前）；至今共发布 5 个版本，其中过去 12 个月发布了 5 个；首次发布于 2026/01/27。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

