browser-use-to-stagehand
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chinesebrowser-use → Stagehand on Browserbase (/browser-use-to-stagehand
)
/browser-use-to-stagehandbrowser-use → Browserbase 上的 Stagehand(/browser-use-to-stagehand
)
/browser-use-to-stagehandConvert a browser-use (Python) script into an idiomatic Stagehand v3 (TypeScript) script on
Browserbase, choosing the right level of determinism at each step rather than producing a
one-to-one agentic copy.
Core principle: browser-use is agentic-by-default (the LLM decides every action). Stagehand
lets you choose how much AI to use. A good migration replaces opaque agent loops with an
inspectable, mostly-deterministic pipeline — using AI only where the page is genuinely
unpredictable. This is a refactor with judgment, not a transpile.
Source of truth & versions. This skill's durable value is the judgment — the determinism spectrum and the decompose-vs-agent decision — not the API specifics, which drift every release. The code mappings here are a snapshot validated against3.6.x and browser-use 0.13.x (2026-06). On any conflict, the live docs win — always verify against the installed package and these sources before emitting code:@browserbasehq/stagehand
- Stagehand v3: https://docs.stagehand.dev/v3 · installed types:
node_modules/@browserbasehq/stagehand- Browserbase: https://docs.browserbase.com
- browser-use: https://docs.browser-use.com
If the installed Stagehand major is not 3, treat this skill as conceptual only and follow the live docs for every signature.
将browser-use(Python)脚本转换为Browserbase上符合规范的**Stagehand v3(TypeScript)**脚本,在每个步骤选择合适的确定性级别,而非生成一对一的智能体副本。
核心原则:browser-use默认是智能体驱动的(LLM决定每一个操作)。Stagehand允许你选择AI的使用程度。优秀的迁移会将不透明的智能体循环替换为可检查、基本确定的流水线——仅在页面真正不可预测的场景下使用AI。这是带有判断的重构,而非转译。
事实来源与版本说明。本技能的持久价值在于判断能力——确定性范围以及分解逻辑与智能体逻辑的决策——而非API细节,这些细节每个版本都会变化。此处的代码映射是针对3.6.x和browser-use 0.13.x(2026-06)验证的快照。若出现任何冲突,以在线文档为准——在生成代码前,请始终对照已安装的包和以下来源进行验证:@browserbasehq/stagehand
- Stagehand v3:https://docs.stagehand.dev/v3 · 已安装类型:
node_modules/@browserbasehq/stagehand- Browserbase:https://docs.browserbase.com
- browser-use:https://docs.browser-use.com
若已安装的Stagehand主版本不是3,则仅将本技能作为概念参考,并严格遵循在线文档中的所有签名。
Reference files (read as needed)
参考文件(按需阅读)
- — the mechanical browser-use → Stagehand mapping: variant detection, the full feature table, before/after code, Browserbase platform options, and v3 version gotchas. Read this for any non-trivial construct.
references/api-mapping.md - — how to choose
references/determinism.mdvsagent()/act/extractvs cachedobserve→observe. The decision tree. Read this when deciding how to translate anact.Agent(task=…) - — the optional "run it on Browserbase, read the logs, then rewrite" workflow for opaque/flaky scripts.
references/trace-assisted.md - — the human migration guide: philosophy shift, feature mapping, the determinism spectrum, and a recommended migration path.
references/guide.md - — a self-contained, tool-agnostic version of this skill; paste it into any AI assistant along with a browser-use script.
references/prompt.md - — before/after script pairs.
EXAMPLES.md
- — browser-use → Stagehand的机械映射:变体检测、完整功能表、代码前后对比、Browserbase平台选项以及v3版本注意事项。处理任何非简单结构时请阅读此文件。
references/api-mapping.md - — 如何选择
references/determinism.mdvsagent()/act/extractvs 缓存的observe→observe。决策树。翻译act时请阅读此文件。Agent(task=…) - — 针对不透明/不稳定脚本的可选工作流:在Browserbase上运行原脚本,读取日志,然后重写。
references/trace-assisted.md - — 人工迁移指南:理念转变、功能映射、确定性范围以及推荐的迁移路径。
references/guide.md - — 本技能的独立、工具无关版本;可将其与browser-use脚本一起粘贴到任何AI助手。
references/prompt.md - — 脚本前后对比示例。
EXAMPLES.md
Workflow
工作流程
1. Get the source
1. 获取源脚本
Obtain the browser-use script(s). If the user only described a script, ask for the file(s). Note
the target: TypeScript Stagehand on Browserbase unless they say otherwise.
First, gate on scope — is this even migratable? Not every browser-use file is anscript. If the source is browser-use running as an MCP server (Agent(task=…), auvx browser-use --mcpconfig) there is no Stagehand equivalent — flag it as out of scope, don't invent one (see api-mapping §3.7b). If the browser-use call is embedded in a larger app (a class/tool wrapper, web route, queue task), convert only the browser-use surface and preserve the surrounding app glue — see api-mapping §3.8.mcpServers
获取browser-use脚本。如果用户仅描述了脚本,请求其文件。注意目标:除非用户另有说明,否则目标为Browserbase上的TypeScript Stagehand。
首先,检查范围——这是否可迁移? 并非所有browser-use文件都是脚本。如果源脚本是作为MCP服务器运行的browser-use(Agent(task=…)、uvx browser-use --mcp配置),则没有对应的Stagehand等效方案——标记为超出范围,不要自行创造(见api-mapping §3.7b)。如果browser-use调用嵌入在更大的应用中(类/工具包装器、Web路由、队列任务),仅转换browser-use相关部分并保留周围的应用粘合代码——见api-mapping §3.8。mcpServers
2. Detect the browser-use variant
2. 检测browser-use变体
Identify legacy (pre-0.12) vs stable vs Rust beta (only when imports come from )
— see api-mapping §1. Note: the classic top-level
surface is alive and well in 0.13.x — alone is not a beta tell; only a
import is. All variants translate identically, so when unsure, proceed with the
stable mapping. Normalize legacy names before translating. State which variant you found.
browser_use.betafrom browser_use import Agent, ChatBrowserUseChatBrowserUsebrowser_use.beta识别旧版(0.12之前)、稳定版还是Rust测试版(仅当导入来自时)——见api-mapping §1。注意:经典的顶层接口在0.13.x中仍在使用——仅不是测试版的标志;只有导入才是。所有变体的转换方式相同,若不确定,按稳定版映射处理。转换前先标准化旧版名称。说明你检测到的变体。
browser_use.betafrom browser_use import Agent, ChatBrowserUseChatBrowserUsebrowser_use.beta3. Inventory the script
3. 梳理脚本内容
Extract a structured inventory before writing any TypeScript:
- Task(s) — the string(s); split each into its implied ordered steps.
task= - Model — the provider + model id.
Chat* - Browser config — local vs /Browserbase; headless; proxies;
cdp_url/user_data_dir.storage_state - Structured output — any Pydantic models.
output_model_schema - Secrets — , env-var usage, login flows.
sensitive_data - Guardrails — ,
allowed_domains.max_steps - Custom actions — /
@tools.actionfunctions, and whether each is a deterministic side-effect or an agent capability.Controller - Setup — , secondary models (
initial_actions,page_extraction_llm).planner_llm
在编写任何TypeScript代码前,提取结构化清单:
- 任务 — 字符串;将每个任务拆分为隐含的有序步骤。
task= - 模型 — 提供商+模型ID。
Chat* - 浏览器配置 — 本地浏览器还是/Browserbase;无头模式;代理;
cdp_url/user_data_dir。storage_state - 结构化输出 — 任何Pydantic模型。
output_model_schema - 密钥 — 、环境变量使用、登录流程。
sensitive_data - 防护机制 — 、
allowed_domains。max_steps - 自定义操作 — /
@tools.action函数,以及每个函数是确定性副作用还是智能体能力。Controller - 设置 — 、二级模型(
initial_actions、page_extraction_llm)。planner_llm
4. Decide the determinism level per step
4. 为每个步骤确定确定性级别
For each step from the inventory, apply the decision tree in determinism.md:
- Navigate to a known URL → on the Stagehand page (no AI).
page.goto(url) - On-page action → ; if it repeats,
act("…")once then replayobserve()(no LLM call).act(action) - Reading data → .
extract("…", zodSchema) - Genuinely open-ended → keep (tightened with
stagehand.agent().execute(...)/maxSteps).systemPrompt
Default to decomposition when the flow is known; keep only where it isn't. For a
first lift-and-shift, a faithful translation is acceptable — say so and note the
optimization path.
agent()agent()对清单中的每个步骤,应用determinism.md中的决策树:
- 导航到已知URL → 使用Stagehand页面的(无需AI)。
page.goto(url) - 页面内操作 → ;若重复执行,先
act("…")一次,然后重放observe()(无需LLM调用)。act(action) - 读取数据 → 。
extract("…", zodSchema) - 真正开放式的任务 → 保留(通过
stagehand.agent().execute(...)/maxSteps限制)。systemPrompt
当流程已知时,默认选择分解逻辑;仅在流程未知时保留。对于首次迁移,忠实的转换是可接受的——说明这一点并标注优化路径。
agent()agent()5. Produce the Stagehand v3 rewrite
5. 生成Stagehand v3重写版本
First, verify the API. Before writing, confirm the exact signatures you're about to use against
the installed package ( types) or https://docs.stagehand.dev/v3.
The mappings below are a 3.6.x snapshot; if anything differs in the installed version, the installed
version wins. Then emit runnable TypeScript. Always:
node_modules/@browserbasehq/stagehand- and
import { Stagehand } from "@browserbasehq/stagehand";when extracting.import { z } from "zod"; - Get the page via .
const page = stagehand.context.pages()[0]; - Call AI methods on the instance: ,
stagehand.act(...),stagehand.extract(...)— neverstagehand.observe(...).page.act(...) - Set the model as a string.
"provider/model" - Default to ; show
env: "BROWSERBASE"as the dev option.env: "LOCAL" - Pass secrets via and
variables, never hardcoded.process.env - at the start,
await stagehand.init()in aawait stagehand.close().finally
Include the project setup so it runs (see the templates below).
首先,验证API。编写前,对照已安装的包(类型)或https://docs.stagehand.dev/v3确认你要使用的准确签名。以下映射是3.6.x的快照;若已安装版本中有任何差异,以已安装版本为准。然后生成可运行的TypeScript代码。始终:
node_modules/@browserbasehq/stagehand- 导入,提取数据时导入
import { Stagehand } from "@browserbasehq/stagehand";。import { z } from "zod"; - 通过获取页面。
const page = stagehand.context.pages()[0]; - 在实例上调用AI方法:、
stagehand.act(...)、stagehand.extract(...)——切勿调用stagehand.observe(...)。page.act(...) - 将模型设置为格式的字符串。
"provider/model" - 默认使用;将
env: "BROWSERBASE"作为开发选项展示。env: "LOCAL" - 通过和
variables传递密钥,切勿硬编码。process.env - 在开头调用,在
await stagehand.init()中调用finally。await stagehand.close()
包含项目设置以便运行(见下方模板)。
6. Write the migration summary
6. 编写迁移摘要
Alongside the code, produce a short summary:
- Variant detected and the determinism choices made (which steps became deterministic vs AI vs agent), with the reasoning.
- Needs human review — anything that didn't map 1:1: lost guardrails, custom-action logic, secondary-model intent, ambiguous task strings.
allowed_domains - Recommended next step — Browserbase Context for auth reuse, caching for production, or the trace-assisted path if the flow was opaque.
随代码一起生成简短摘要:
- 检测到的变体以及做出的确定性选择(哪些步骤转为确定性逻辑、AI逻辑还是智能体逻辑),并说明理由。
- 需要人工审核的内容——任何无法一对一映射的部分:丢失的防护机制、自定义操作逻辑、二级模型意图、模糊的任务字符串。
allowed_domains - 推荐下一步——用于身份复用的Browserbase Context、生产环境的缓存,或如果流程不透明则使用trace-assisted路径。
7. Offer the trace-assisted path (only if warranted)
7. 提供trace-assisted路径(仅在必要时)
If the source was one large opaque , was flaky, or your rewrite can't be confidently
mapped, offer the trace-assisted workflow (trace-assisted.md): run the original on Browserbase, pull
, and rewrite from observed behavior. Don't run anything without the user's go-ahead.
agent(task=…)sessions.logs.list如果源脚本是一个大型不透明的、不稳定,或你的重写无法准确映射,提供trace-assisted工作流(trace-assisted.md):在Browserbase上运行原脚本,拉取,根据观察到的行为重写。未经用户许可,不要运行任何内容。
agent(task=…)sessions.logs.listOutput templates
输出模板
package.jsonjson
{
"name": "stagehand-migration",
"type": "module",
"scripts": { "start": "tsx index.ts" },
"dependencies": {
"@browserbasehq/stagehand": "^3.0.0",
"dotenv": "^16.0.0",
"zod": "^3.25.0"
},
"devDependencies": { "tsx": "^4.0.0", "typescript": "^5.0.0" }
}Add(Vercel AI SDK) only if a custom browser-use action maps to an agent"ai": "^5.0.0". Pin v5, not v4 — Stagehand 3.6.x bundlestoolv5 and typesaias the v5agent({ tools }), where a tool's schema field isToolSet. The v4inputSchemahelper emitstool()instead and will fail to type-check against Stagehand's v5parameters. If you can't control the hoistedToolSetversion, skip theaihelper and pass a plain objecttool()— it satisfies the v5{ description, inputSchema: zodSchema, execute }regardless of whichToolSetmajor resolves.ai
.envbash
BROWSERBASE_API_KEY=...
BROWSERBASE_PROJECT_ID=...
ANTHROPIC_API_KEY=... # or the provider matching your model stringindex.tstypescript
import "dotenv/config";
import { Stagehand } from "@browserbasehq/stagehand";
import { z } from "zod";
async function main() {
const stagehand = new Stagehand({
env: "BROWSERBASE",
model: "anthropic/claude-sonnet-4-6",
});
await stagehand.init();
try {
const page = stagehand.context.pages()[0];
await page.goto("https://example.com"); // deterministic skeleton
await stagehand.act("…"); // AI where the page varies
const data = await stagehand.extract("…", z.object({ /* … */ })); // structured reads
console.log(data);
} finally {
await stagehand.close();
}
}
main().catch((err) => { console.error(err); process.exit(1); });package.jsonjson
{
"name": "stagehand-migration",
"type": "module",
"scripts": { "start": "tsx index.ts" },
"dependencies": {
"@browserbasehq/stagehand": "^3.0.0",
"dotenv": "^16.0.0",
"zod": "^3.25.0"
},
"devDependencies": { "tsx": "^4.0.0", "typescript": "^5.0.0" }
}仅当自定义browser-use操作映射到智能体时,添加tool(Vercel AI SDK)。固定v5版本,不要v4——Stagehand 3.6.x捆绑了"ai": "^5.0.0"v5,并将ai的类型定义为v5的agent({ tools }),其中工具的schema字段为**ToolSet。v4的inputSchema助手会生成tool()而非parameters,将无法通过Stagehand v5inputSchema的类型检查**。若无法控制ToolSet的版本,跳过ai助手,直接传递普通对象tool()——无论解析到哪个{ description, inputSchema: zodSchema, execute }主版本,它都能满足v5ai的要求。ToolSet
.envbash
BROWSERBASE_API_KEY=...
BROWSERBASE_PROJECT_ID=...
ANTHROPIC_API_KEY=... # 或与你的模型字符串匹配的提供商密钥index.tstypescript
import "dotenv/config";
import { Stagehand } from "@browserbasehq/stagehand";
import { z } from "zod";
async function main() {
const stagehand = new Stagehand({
env: "BROWSERBASE",
model: "anthropic/claude-sonnet-4-6",
});
await stagehand.init();
try {
const page = stagehand.context.pages()[0];
await page.goto("https://example.com"); // 确定性骨架
await stagehand.act("…"); // 在页面变化的场景使用AI
const data = await stagehand.extract("…", z.object({ /* … */ })); // 结构化读取
console.log(data);
} finally {
await stagehand.close();
}
}
main().catch((err) => { console.error(err); process.exit(1); });Validation checklist (before declaring done)
验证清单(完成前检查)
- AI methods are on the instance (), not the page.
stagehand.act/extract/observe - Page obtained via .
stagehand.context.pages()[0] - Model is a string; the matching provider key is in
"provider/model"..env - uses a zod schema;
extractis in dependencies.zod - Secrets use +
variables; nothing hardcoded.process.env - /
init()present;close()inclose().finally - Each browser-use step is accounted for, placed deliberately on the determinism spectrum.
- Migration summary lists determinism choices and "needs human review" items.
- AI方法调用在实例上(),而非页面上。
stagehand.act/extract/observe - 通过获取页面。
stagehand.context.pages()[0] - 模型为格式的字符串;
"provider/model"中包含匹配的提供商密钥。.env - 使用zod schema;
extract已添加到依赖中。zod - 密钥使用+
variables;无硬编码内容。process.env - 存在/
init();close()在close()中。finally - 每个browser-use步骤都已处理,并被刻意放置在确定性范围的对应位置。
- 迁移摘要列出了确定性选择和“需要人工审核”的项目。
Common mistakes to avoid
需避免的常见错误
- Copying v2 syntax (,
page.act(),stagehand.page/modelName,modelClientOptions) from old blog posts. Use v3 — see api-mapping "Version notes".enableCaching - Translating every step into — navigate with
act()and cache repeatable steps viapage.goto→observe; don't spend an LLM call on every action.act - Defaulting everything to — that just reproduces browser-use's non-determinism in a new framework. Decompose where the flow is known.
agent() - Silently dropping — Stagehand has no domain firewall; flag it for review.
allowed_domains - Inventing Browserbase/Stagehand options — if unsure of a field, check https://docs.stagehand.dev/v3 / https://docs.browserbase.com rather than guessing.
- 复制v2语法(、
page.act()、stagehand.page/modelName、modelClientOptions)来自旧博客文章。使用v3语法——见api-mapping中的“版本说明”。enableCaching - 将每个步骤都翻译为——使用
act()导航,通过page.goto→observe缓存可重复步骤;不要为每个操作都调用LLM。act - 默认所有步骤都使用——这只会在新框架中重现browser-use的非确定性。在流程已知时进行分解。
agent() - 静默丢弃——Stagehand没有域名防火墙;标记该内容以便审核。
allowed_domains - 自行发明Browserbase/Stagehand选项——若不确定某个字段,查看https://docs.stagehand.dev/v3 / https://docs.browserbase.com,不要猜测。",