選項
首頁首頁 Skill 開發者工具 browser-use-to-stagehand

browser-use-to-stagehand

browserbase/skills browserbase/skills

將 Browserbase 上的瀏覽器使用(Python)瀏覽器自動化腳本轉換為 Stagehand v3(TypeScript),並在可行情況下,以確定性管線取代不透明的代理循環。

...展開全部
0
更新時間 2026-09-30

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

將 browser-use(Python)腳本轉換為 Browserbase 上的符合 Stagehand v3 慣用風格(TypeScript)腳本, 在每個步驟中選擇適當的決定性程度,而非產生 一對一的代理式複本。

核心原則:browser-use 預設為代理式運作(由大型語言模型決定每項動作)。Stagehand 則讓您自行選擇 AI 的介入程度。 成功的遷移應將不透明的代理迴圈替換為 可檢視且大多具決定性的處理流程——僅在頁面確實 難以預測時才使用 AI。這是一項需運用判斷力的重構,而非單純的轉譯。

權威來源與版本。這項技能的持久價值在於判斷力——即決定論 的範圍以及「分解 vs 代理」的決策——而非 API 的具體細節,因為這些細節會隨著每次發布而變動。 此處的程式碼對應關係是針對 @browserbasehq/stagehand 3.6.x 及 browser-use 0.13.x(2026-06)驗證過的快照。若有任何衝突,以線上文件為準——在產生程式碼前,請務必根據 已安裝的套件及這些來源進行驗證:

  • 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,請將此技能視為僅具概念性,並針對每個簽名參照 最新文件。

參考文件(視需要閱讀)

  • 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 — 此技能的自包含、不依賴特定工具的版本; 可將其連同瀏覽器使用腳本一併貼入任何 AI 助理中。
  • EXAMPLES.md — 腳本的「遷移前/遷移後」對照組。

工作流程

1. 取得原始碼

取得瀏覽器使用腳本。若使用者僅描述腳本內容,請要求其提供檔案。請注意 目標格式:除非另有說明,否則應採用基於 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. 偵測 browser-use 的變體

區分舊版(0.12 之前)、穩定版與 Rust 測試版(僅當匯入來源來自 browser_use.beta) — 參見 api-mapping §1。注意:經典的頂層 from browser_use import Agent, ChatBrowserUse 介面在 0.13.x 版本中依然有效 — ChatBrowserUse 單憑此點無法判斷是否為 beta 版本;唯有 browser_use.beta import 才算。所有變體的轉換方式皆相同,因此若不確定,請採用 穩定版對應規則。轉換前請先將舊版名稱正規化。請註明您發現的變體類型。

3. 清點腳本

在編寫任何 TypeScript 之前,請先整理出結構化的清單:

  • 任務 — 將 task= 字串;將每個字串拆解為其隱含的有序步驟。
  • 模型 — 由 Chat* 提供者 + 模型 ID。
  • 瀏覽器配置 — 本地 vs 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. 決定每個步驟的確定性層級

針對清單中的每個步驟,套用 determinism.md 中的決策樹:

  • 導航至已知 URL → page.goto(url) 在 Stagehand 頁面(不使用 AI)。
  • 頁面內操作 → act("…");若需重複執行, observe() 執行一次後重播 act(action) (不呼叫大型語言模型)。
  • 讀取資料 → extract("…", zodSchema).
  • 真正開放式 → 維持 stagehand.agent().execute(...) (透過 maxSteps/systemPrompt).

當流程已知時預設進行分解;僅在 agent() 僅在未知時才進行分解。對於 首次「移轉與移植」,忠實的 agent() 轉換即可接受——請明確說明並註明 優化路徑。

5. 產出 Stagehand v3 重寫版本

首先,驗證 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() 在開頭, await stagehand.close() 在 finally.

包含專案設定以確保其能執行(請參閱下方的範本)。

6. 撰寫遷移摘要

在程式碼旁,撰寫一份簡短摘要:

  • 已偵測到的變體,以及所做的決定性選擇(哪些步驟轉為決定性、哪些採用 AI、哪些由代理處理),並附上理由說明。
  • 需經人工審查——任何未達成 1:1 對應之處:遺失的 allowed_domains 安全防護措施、 自訂動作邏輯、次級模型意圖、含糊的任務字串。
  • 建議的下一步 — 採用 Browserbase Context 進行授權重複使用、生產環境的快取,或若流程不透明時採用 追蹤輔助路徑。

7. 提供「追蹤輔助路徑」(僅在合理情況下)

若原始程式碼為單一大型且不透明的 agent(task=…)、運作不穩定,或您的重寫無法確切 映射時,請提供「追蹤輔助工作流程」(trace-assisted.md):在 Browserbase 上執行原始程式碼,擷取 sessions.logs.list,並根據觀察到的行為進行重寫。未經使用者同意,請勿執行任何操作。

輸出範本

package.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" }
}

僅當 "ai": "^5.0.0" (Vercel AI SDK)僅在自訂的瀏覽器使用動作可映射至特定代理時才加入 tool時,才添加此項目。請固定使用 v5 而非 v4 — Stagehand 3.6.x 捆綁了 ai v5 並將類型 agent({ tools }) 作為 v5 ToolSet,其中工具的 schema 欄位為 inputSchema。v4 tool() 輔助程式會發送 parameters ,且在與 Stagehand 的 v5 ToolSet。若您無法 控制被提升的 ai ,請跳過 tool() 輔助函式,並傳入一個純粹的物件 { description, inputSchema: zodSchema, execute } ——它能滿足 v5 ToolSet ,無論是哪個 ai 主要解析結果為何。

.env

BROWSERBASE_API_KEY=...
BROWSERBASE_PROJECT_ID=...
ANTHROPIC_API_KEY=...   # or the provider matching your model string

index.ts 骨架(已分解,首選形式)

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); });

驗證清單(在宣告完成之前)

  • AI 方法是針對實例(stagehand.act/extract/observe),而非頁面。
  • 透過 stagehand.context.pages()[0].
  • Model 是一個 "provider/model" 字串;對應的提供者金鑰位於 .env.
  • extract 使用 Zod 模式; zod 位於依賴項中。
  • 機密資訊使用 variables + process.env;沒有硬編碼的內容。
  • init() / close() 存在; close() 位於 finally.
  • 每個瀏覽器使用步驟皆已納入考量,並刻意置於確定性光譜之上。
  • 遷移摘要列出了確定性相關的選項以及「需人工審查」的項目。

應避免的常見錯誤

  • 從舊的部落格文章中複製 v2 語法(page.act(), stagehand.page, modelName/modelClientOptions, enableCaching) 從舊部落格文章中複製。請使用 v3 — 請參閱 API 對應表的「版本說明」。
  • 將每個步驟轉換為 act() — 使用 page.goto 進行導航,並透過 observe→act;不要對每個操作都消耗一個 LLM 呼叫。
  • 將所有內容預設為 agent() —— 這只是將瀏覽器使用的非確定性複製到 新框架中。在流程已知的情況下進行分解。
  • 默默捨棄 allowed_domains —— Stagehand 沒有領域防火牆;應標記該處以供審查。
  • 自行發明 Browserbase/Stagehand 選項 — 若不確定某個欄位,請查閱 https://docs.stagehand.dev/v3 / https://docs.browserbase.com 而非憑空猜測。
在 GitHub 上查看
---
name: browser-use-to-stagehand
description: Convert browser-use (Python) browser-automation scripts to Stagehand v3 (TypeScript) on Browserbase, replacing opaque agent loops with deterministic pipelines where possible.
license: MIT
---

# browser-use → Stagehand on Browserbase (`/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:
> - 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.

## Reference files (read as needed)

- [`references/api-mapping.md`](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`](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`](references/trace-assisted.md) — the optional "run it on
  Browserbase, read the logs, then rewrite" workflow for opaque/flaky scripts.
- [`references/guide.md`](references/guide.md) — the human migration guide: philosophy shift,
  feature mapping, the determinism spectrum, and a recommended migration path.
- [`references/prompt.md`](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`](EXAMPLES.md) — before/after script pairs.

## Workflow

### 1. Get the source
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.

### 2. Detect the browser-use variant
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.

### 3. Inventory the script
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`).

### 4. Decide the determinism level per step
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.

### 5. Produce the Stagehand v3 rewrite
**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).

### 6. Write the migration summary
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.

### 7. Offer the trace-assisted path (only if warranted)
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.

## 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); });
```

## 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.

## 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.

安裝 browser-use-to-stagehand

請下載並將技能檔案解壓縮至您的 .claude/skills/ 目錄中。

下載 ZIP

複製儲存庫並將技能檔案複製到您的專案中。

git clone https://github.com/browserbase/skills/tree/main/skills/browser-use-to-stagehand # Copy SKILL.md to your .claude/skills/ directory

複製 複製
快速設定: 將技能資料夾複製到 .claude/skills/ Claude 會自動偵測並使用該技能
儲存庫 browserbase/skills

相關技能

algorithmic-art
更新時間 2026-08-27
systematic-debugging
更新時間 2026-09-03
tech-debt-tracker
更新時間 2026-08-29
continual-learning
更新時間 2026-09-10
OR