browser-use-to-stagehand
browserbase/skills
Browserbase에서 브라우저 사용(Python) 자동화 스크립트를 Stagehand v3(TypeScript)로 변환하고, 가능한 경우 불투명한 에이전트 루프를 결정론적 파이프라인으로 대체합니다.
...모든 것을 확장하십시오browser-use → Browserbase의 Stagehand (/browser-use-to-stagehand)
브라우저베이스에서 browser-use(Python) 스크립트를 Stagehand v3(TypeScript)의 관용적인 스크립트로 변환하며, 일대일 에이전트 방식의 복제본을 생성하기보다는 각 단계에서 적절한 수준의 결정론을 선택합니다.
핵심 원칙: browser-use는 기본적으로 에이전트 기반입니다(LLM이 모든 행동을 결정합니다). Stagehand를 사용하면 AI를 어느 정도 활용할지 선택할 수 있습니다. 성공적인 마이그레이션은 불투명한 에이전트 루프를 검토 가능하고 대체로 결정론적인 파이프라인으로 대체하며, 페이지가 진정으로 예측 불가능한 경우에만 AI를 사용합니다. 이는 단순한 트랜스파일링이 아닌, 판단을 동반한 리팩토링입니다.
진실의 원천 및 버전. 이 기술의 지속적인 가치는 판단력, 즉 결정론의 스펙트럼과 ‘분해 대 에이전트’ 결정에 있으며, 릴리스마다 변동하는 API 세부 사항에 있는 것이 아닙니다. 여기에 제시된 코드 매핑은
@browserbasehq/stagehand3.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()vsact/extract/observevs 캐시된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,mcpServersconfig), Stagehand에 상응하는 기능이 없으므로 이를 범위 외로 표시하고, 임의로 만들지 마십시오(api-mapping §3.7b 참조). browser-use 호출이 더 큰 앱(클래스/도구 래퍼, 웹 라우트, 큐 태스크)에 내장된 경우, browser-use 인터페이스만 변환하고 주변 앱의 연결 코드는 그대로 유지하십시오 — api-mapping §3.8 참조.
2. browser-use 변형 감지
레거시(0.12 이전)와 안정 버전, Rust 베타(import가 browser_use.beta)
— api-mapping §1 참조. 참고: 기존의 최상위 from browser_use import Agent, ChatBrowserUse
표면은 0.13.x에서도 여전히 유효합니다 — ChatBrowserUse 그 자체만으로는 베타 버전임을 알 수 있는 지표가 아닙니다. 오직
browser_use.beta import가 베타의 지표가 됩니다. 모든 변형은 동일하게 변환되므로, 확실하지 않은 경우
안정 버전의 매핑을 따르십시오. 변환 전에 레거시 이름을 정규화하십시오. 발견한 변형을 명시하십시오.
3. 스크립트 목록 작성
TypeScript를 작성하기 전에 구조화된 작업 목록을 추출하십시오:
- 작업(들) —
task=문자열; 각 문자열을 내포된 순차적 단계로 분할하십시오. - 모델 —
Chat*제공자 + 모델 ID. - 브라우저 구성 — 로컬 대
cdp_url/Browserbase; 헤드리스; 프록시;user_data_dir/storage_state. - 구조화된 출력 — 모든
output_model_schemaPydantic 모델. - 비밀 정보 —
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)(LLM 호출 없음). - 데이터 읽기 →
extract("…", zodSchema). - 진정으로 개방형 → 유지
stagehand.agent().execute(...)(다음 조건으로 강화됨maxSteps/systemPrompt).
흐름이 알려진 경우 기본적으로 분해 처리; 그렇지 않은 경우에만 agent() 알 수 없는 경우에만 적용.
첫 번째 리프트 앤 시프트(lift-and-shift)의 경우, 원본을 충실히 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에만 추가하십시오. v4가 아닌 v5를 고정하십시오 — Stagehand 3.6.x는aiv5를 번들로 제공하며, 유형은agent({ tools })v5로 지정됩니다ToolSet로 묶어 제공하며, 여기서 도구의 스키마 필드는inputSchema입니다. v4tool()헬퍼는parameters를 반환하며, Stagehand의 v5에 대한 타입 검사에서는 실패합니다ToolSet에 대한 타입 검사에 실패합니다. 호이스팅된 버전을 제어할 수 없다면ai버전을 제어할 수 없다면,tool()헬퍼를 건너뛰고 일반 객체를{ description, inputSchema: zodSchema, execute }— 이는 v5ToolSet를 충족합니다ai메이저가 해결되든 상관없이 v5를 충족합니다.
.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. -
extractzod 스키마를 사용하며;zod의존성에 포함되어 있습니다. - 시크릿은
variables+process.env; 하드코딩된 내용은 없습니다. -
init()/close()존재함;close()infinally. - 각 브라우저 사용 단계가 모두 고려되었으며, 결정론 스펙트럼 상에서 신중하게 배치되었습니다.
- 마이그레이션 요약에는 결정론 관련 선택 사항과 “사람의 검토가 필요한” 항목이 나열되어 있습니다.
피해야 할 흔한 실수
- 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를 확인하십시오.
---
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.
모든 파일
8개 파일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
복사





집
