对流相控手
Convex应用程序的AI-动力浏览器自动化. 提取数据,执行动作,并使用自然语言实现工作流程自动化 - 不需要Playwright知识.
特征
- 简单 API - 用简单的英语描述你想要什么
- 类型安全 - 用Zod schemas提供全部类型脚本支持
- 会话管理 - 在多个操作中重复使用浏览器会话
- 代理模式 - 自动多步骤任务执行
- 由 Stagehand 提供动力 - 使用 阶段手 (原始内容存档于2013-10-12) (英语). REST API
快速启动
1. 安装组件
npm install @browserbasehq/convex-stagehand zod
2. 配置对流
将组件添加到您的 convex/convex.config.ts数字 :
import { defineApp } from "convex/server";
import stagehand from "convex-stagehand/convex.config";
const app = defineApp();
app.use(stagehand, { name: "stagehand" });
export default app;
3. 设置环境变量
把这些添加到您的 凸起板 环境变量:
| 变量 | 说明 |
|---|---|
BROWSERBASE_API_KEY | 您的浏览器库 API 密钥 |
BROWSERBASE_PROJECT_ID | 您的浏览器项目 ID |
MODEL_API_KEY | 您的 LLM 提供者 API 密钥( OpenAI, Anthropic等) |
4. 使用该构成部分
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)
启动一个新的浏览器会话 。 返回会话信息,用于其他操作.
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- 要导航的 URLbrowserbaseSessionID- 可选:恢复现有的浏览器会话options.timeout- 导航超时(以毫秒计)options.waitUntil- 何时考虑完成导航:"load", (中文(简体) ),"domcontentloaded",或"networkidle"options.domSettleTimeoutMs- DOM 在考虑加载页面前结算的超时options.selfHeal- 启用自愈能力,使自动化更加健全options.systemPrompt- 自定义系统在会话中提示AI的行为
回返情况:
{
sessionId: string; // Use with other operations
cdpUrl?: string; // For advanced Playwright/Puppeteer usage
}
endSession(ctx, args)
结束浏览器会话 .
await stagehand.endSession(ctx, { sessionId: session.sessionId });
参数:
sessionId- 会议结束
回返情况: { success: boolean }
extract(ctx, args)
从使用AI的网页中提取结构化数据.
// 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)
使用自然语言执行浏览器动作 .
// 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 '[email protected]'",
});
参数:
sessionId- 可选:利用现有会话url- 要导航的 URL( 如果没有会话需要的话) (d) 国家action- 执行行动的自然语言描述options.timeout- 导航超时(以毫秒计)options.waitUntil- 何时考虑完成导航
回返情况:
{
success: boolean;
message: string;
actionDescription: string;
}
observe(ctx, args)
在网页上查找可用的动作 .
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- 何时考虑完成导航
回返情况:
Array<{
description: string;
selector: string;
method: string;
arguments?: string[];
}>
agent(ctx, args)
使用AI代理执行自动多步浏览器自动化. 代理人解释指令,决定要采取的行动.
// 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- 何时考虑完成导航
回返情况:
{
actions: Array<{
type: string;
action?: string;
reasoning?: string;
timeMs?: number;
}>;
completed: boolean;
message: string;
success: boolean;
}
实例
简单提取( 自动会话)
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(),
}))
})
});
人工会话管理
当您需要执行多个操作时, 请使用会话管理
// 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代理商找出如何完成一项复杂的任务:
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动作中工作,呼吁:
// 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 支持结构化产出:
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",
});
获得支持的模型和提供者的完整清单,见 模型文档。 。 。 .
所需资源
如何运作
此组件使用 阶段手 REST API 以启动浏览器自动化。 每个操作 :
- 通过浏览器库启动云浏览器会话( 或重新使用已有的会话)
- 导航到目标 URL
- 使用AI来理解页面并进行请求操作
- 可选结束会话并返回结果
通过会话管理,您控制会话开始和结束时,允许您在多个操作中保持浏览器状态.
发展
构成部分结构
该组件通过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 :
// User calls:
stagehand.extract(ctx, {...})
// Internally calls:
ctx.runAction(component.lib.extract, {...})
建设构成部分
为在当地建立这一构成部分:
# 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/ 目录 :
git clone https://github.com/browserbase/integrations
cd integrations/packages/convex-stagehand/example
npm install
npm run dev
例子包括:
- HackerNews 与 AI 的故事提取
- 使用 Zod schemas 提取安全数据
- 带有 Convex 的数据库持久性
- 实时更新和自动刷新
许可证
麻省理工学院