browser-use-to-stagehand

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

browser-use → Stagehand on Browserbase (
/browser-use-to-stagehand
)

browser-use → Browserbase 上的 Stagehand(
/browser-use-to-stagehand

Convert 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 against
@browserbasehq/stagehand
3.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:
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细节,这些细节每个版本都会变化。此处的代码映射是针对
@browserbasehq/stagehand
3.6.x和browser-use 0.13.x(2026-06)验证的快照
。若出现任何冲突,以在线文档为准——在生成代码前,请始终对照已安装的包和以下来源进行验证:
若已安装的Stagehand主版本不是3,则仅将本技能作为概念参考,并严格遵循在线文档中的所有签名。

Reference files (read as needed)

参考文件(按需阅读)

  • references/api-mapping.md
    — 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/determinism.md
    — how to choose
    agent()
    vs
    act
    /
    extract
    /
    observe
    vs cached
    observe
    act
    . The decision tree. Read this when deciding how to translate an
    Agent(task=…)
    .
  • references/trace-assisted.md
    — the optional "run it on Browserbase, read the logs, then rewrite" workflow for opaque/flaky scripts.
  • references/guide.md
    — the human migration guide: philosophy shift, feature mapping, the determinism spectrum, and a recommended migration path.
  • references/prompt.md
    — a self-contained, tool-agnostic version of this skill; paste it into any AI assistant along with a browser-use script.
  • EXAMPLES.md
    — before/after script pairs.
  • references/api-mapping.md
    — browser-use → Stagehand的机械映射:变体检测、完整功能表、代码前后对比、Browserbase平台选项以及v3版本注意事项。处理任何非简单结构时请阅读此文件
  • references/determinism.md
    — 如何选择
    agent()
    vs
    act
    /
    extract
    /
    observe
    vs 缓存的
    observe
    act
    。决策树。翻译
    Agent(task=…)
    时请阅读此文件
  • references/trace-assisted.md
    — 针对不透明/不稳定脚本的可选工作流:在Browserbase上运行原脚本,读取日志,然后重写。
  • references/guide.md
    — 人工迁移指南:理念转变、功能映射、确定性范围以及推荐的迁移路径。
  • references/prompt.md
    — 本技能的独立、工具无关版本;可将其与browser-use脚本一起粘贴到任何AI助手。
  • 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 an
Agent(task=…)
script. If the source is browser-use running as an MCP server (
uvx browser-use --mcp
, a
mcpServers
config) 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.
获取browser-use脚本。如果用户仅描述了脚本,请求其文件。注意目标:除非用户另有说明,否则目标为Browserbase上的TypeScript Stagehand
首先,检查范围——这是否可迁移? 并非所有browser-use文件都是
Agent(task=…)
脚本。如果源脚本是作为MCP服务器运行的browser-use
uvx browser-use --mcp
mcpServers
配置),则没有对应的Stagehand等效方案——标记为超出范围,不要自行创造(见api-mapping §3.7b)。如果browser-use调用嵌入在更大的应用中(类/工具包装器、Web路由、队列任务),仅转换browser-use相关部分并保留周围的应用粘合代码——见api-mapping §3.8。

2. Detect the browser-use variant

2. 检测browser-use变体

Identify legacy (pre-0.12) vs stable vs Rust beta (only when imports come from
browser_use.beta
) — see api-mapping §1. Note: the classic top-level
from browser_use import Agent, ChatBrowserUse
surface is alive and well in 0.13.x —
ChatBrowserUse
alone is not a beta tell; only a
browser_use.beta
import is. All variants translate identically, so when unsure, proceed with the stable mapping. Normalize legacy names before translating. State which variant you found.
识别旧版(0.12之前)、稳定版还是Rust测试版(仅当导入来自
browser_use.beta
时)——见api-mapping §1。注意:经典的顶层
from browser_use import Agent, ChatBrowserUse
接口在0.13.x中仍在使用——仅
ChatBrowserUse
不是测试版的标志;只有
browser_use.beta
导入才是。所有变体的转换方式相同,若不确定,按稳定版映射处理。转换前先标准化旧版名称。说明你检测到的变体。

3. Inventory the script

3. 梳理脚本内容

Extract a structured inventory before writing any TypeScript:
  • Task(s) — the
    task=
    string(s); split each into its implied ordered steps.
  • Model — the
    Chat*
    provider + model id.
  • Browser config — local vs
    cdp_url
    /Browserbase; headless; proxies;
    user_data_dir
    /
    storage_state
    .
  • Structured output — any
    output_model_schema
    Pydantic models.
  • Secrets
    sensitive_data
    , env-var usage, login flows.
  • Guardrails
    allowed_domains
    ,
    max_steps
    .
  • Custom actions
    @tools.action
    /
    Controller
    functions, and whether each is a deterministic side-effect or an agent capability.
  • Setup
    initial_actions
    , secondary models (
    page_extraction_llm
    ,
    planner_llm
    ).
在编写任何TypeScript代码前,提取结构化清单:
  • 任务
    task=
    字符串;将每个任务拆分为隐含的有序步骤。
  • 模型
    Chat*
    提供商+模型ID。
  • 浏览器配置 — 本地浏览器还是
    cdp_url
    /Browserbase;无头模式;代理;
    user_data_dir
    /
    storage_state
  • 结构化输出 — 任何
    output_model_schema
    Pydantic模型。
  • 密钥
    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 →
    page.goto(url)
    on the Stagehand page (no AI).
  • On-page action →
    act("…")
    ; if it repeats,
    observe()
    once then replay
    act(action)
    (no LLM call).
  • Reading data →
    extract("…", zodSchema)
    .
  • Genuinely open-ended → keep
    stagehand.agent().execute(...)
    (tightened with
    maxSteps
    /
    systemPrompt
    ).
Default to decomposition when the flow is known; keep
agent()
only where it isn't. For a first lift-and-shift, a faithful
agent()
translation is acceptable — say so and note the optimization path.
对清单中的每个步骤,应用determinism.md中的决策树:
  • 导航到已知URL → 使用Stagehand页面的
    page.goto(url)
    (无需AI)。
  • 页面内操作 →
    act("…")
    ;若重复执行,先
    observe()
    一次,然后重放
    act(action)
    (无需LLM调用)。
  • 读取数据 →
    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 (
node_modules/@browserbasehq/stagehand
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:
  • import { Stagehand } from "@browserbasehq/stagehand";
    and
    import { z } from "zod";
    when extracting.
  • Get the page via
    const page = stagehand.context.pages()[0];
    .
  • Call AI methods on the instance:
    stagehand.act(...)
    ,
    stagehand.extract(...)
    ,
    stagehand.observe(...)
    never
    page.act(...)
    .
  • Set the model as a
    "provider/model"
    string.
  • Default to
    env: "BROWSERBASE"
    ; show
    env: "LOCAL"
    as the dev option.
  • Pass secrets via
    variables
    and
    process.env
    , never hardcoded.
  • await stagehand.init()
    at the start,
    await stagehand.close()
    in a
    finally
    .
Include the project setup so it runs (see the templates below).
首先,验证API。编写前,对照已安装的包(
node_modules/@browserbasehq/stagehand
类型)或https://docs.stagehand.dev/v3确认你要使用的准确签名。以下映射是3.6.x的快照;若已安装版本中有任何差异,以已安装版本为准。然后生成可运行的TypeScript代码。始终:
  • 导入
    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
    allowed_domains
    guardrails, custom-action logic, secondary-model intent, ambiguous task strings.
  • 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
agent(task=…)
, was flaky, or your rewrite can't be confidently mapped, offer the trace-assisted workflow (trace-assisted.md): run the original on Browserbase, pull
sessions.logs.list
, and rewrite from observed behavior. Don't run anything without the user's go-ahead.
如果源脚本是一个大型不透明的
agent(task=…)
、不稳定,或你的重写无法准确映射,提供trace-assisted工作流(trace-assisted.md):在Browserbase上运行原脚本,拉取
sessions.logs.list
,根据观察到的行为重写。未经用户许可,不要运行任何内容。

Output templates

输出模板

package.json
json
{
  "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
"ai": "^5.0.0"
(Vercel AI SDK) only if a custom browser-use action maps to an agent
tool
. Pin v5, not v4 — Stagehand 3.6.x bundles
ai
v5 and types
agent({ tools })
as the v5
ToolSet
, where a tool's schema field is
inputSchema
. The v4
tool()
helper emits
parameters
instead and will fail to type-check against Stagehand's v5
ToolSet
. If you can't control the hoisted
ai
version, skip the
tool()
helper and pass a plain object
{ description, inputSchema: zodSchema, execute }
— it satisfies the v5
ToolSet
regardless of which
ai
major resolves.
.env
bash
BROWSERBASE_API_KEY=...
BROWSERBASE_PROJECT_ID=...
ANTHROPIC_API_KEY=...   # or the provider matching your model string
index.ts
skeleton
(decomposed, the preferred shape)
typescript
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.json
json
{
  "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
时,添加
"ai": "^5.0.0"
(Vercel AI SDK)。固定v5版本,不要v4——Stagehand 3.6.x捆绑了
ai
v5,并将
agent({ tools })
的类型定义为v5的
ToolSet
,其中工具的schema字段为**
inputSchema
。v4的
tool()
助手会生成
parameters
而非
inputSchema
,将
无法通过Stagehand v5
ToolSet
的类型检查**。若无法控制
ai
的版本,跳过
tool()
助手,直接传递普通对象
{ description, inputSchema: zodSchema, execute }
——无论解析到哪个
ai
主版本,它都能满足v5
ToolSet
的要求。
.env
bash
BROWSERBASE_API_KEY=...
BROWSERBASE_PROJECT_ID=...
ANTHROPIC_API_KEY=...   # 或与你的模型字符串匹配的提供商密钥
index.ts
骨架
(分解后的首选结构)
typescript
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 (
    stagehand.act/extract/observe
    ), not the page.
  • Page obtained via
    stagehand.context.pages()[0]
    .
  • Model is a
    "provider/model"
    string; the matching provider key is in
    .env
    .
  • extract
    uses a zod schema;
    zod
    is in dependencies.
  • Secrets use
    variables
    +
    process.env
    ; nothing hardcoded.
  • init()
    /
    close()
    present;
    close()
    in
    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
    中包含匹配的提供商密钥。
  • extract
    使用zod schema;
    zod
    已添加到依赖中。
  • 密钥使用
    variables
    +
    process.env
    ;无硬编码内容。
  • 存在
    init()
    /
    close()
    close()
    finally
    中。
  • 每个browser-use步骤都已处理,并被刻意放置在确定性范围的对应位置。
  • 迁移摘要列出了确定性选择和“需要人工审核”的项目。

Common mistakes to avoid

需避免的常见错误

  • Copying v2 syntax (
    page.act()
    ,
    stagehand.page
    ,
    modelName
    /
    modelClientOptions
    ,
    enableCaching
    ) from old blog posts. Use v3 — see api-mapping "Version notes".
  • Translating every step into
    act()
    — navigate with
    page.goto
    and cache repeatable steps via
    observe
    act
    ; don't spend an LLM call on every action.
  • Defaulting everything to
    agent()
    — that just reproduces browser-use's non-determinism in a new framework. Decompose where the flow is known.
  • Silently dropping
    allowed_domains
    — Stagehand has no domain firewall; flag it for review.
  • 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
    enableCaching
    )来自旧博客文章。使用v3语法——见api-mapping中的“版本说明”。
  • 将每个步骤都翻译为
    act()
    ——使用
    page.goto
    导航,通过
    observe
    act
    缓存可重复步骤;不要为每个操作都调用LLM。
  • 默认所有步骤都使用
    agent()
    ——这只会在新框架中重现browser-use的非确定性。在流程已知时进行分解。
  • 静默丢弃
    allowed_domains
    ——Stagehand没有域名防火墙;标记该内容以便审核。
  • 自行发明Browserbase/Stagehand选项——若不确定某个字段,查看https://docs.stagehand.dev/v3 / https://docs.browserbase.com,不要猜测。",