跳至主要內容

StagehandBrowser 類別

StagehandBrowser 類別使用 Stagehand 提供 AI 驅動的瀏覽器自動化。它使用自然語言 instructions 進行互動,而不是 element ref。

希望 AI 從自然語言解讀並執行瀏覽器動作時,請使用 StagehandBrowser。使用 element ref 的確定性自動化請參閱 AgentBrowser

使用範例
「使用範例」的直接連結

src/mastra/agents/index.ts
import { Agent } from '@mastra/core/agent'
import { StagehandBrowser } from '@mastra/stagehand'

const browser = new StagehandBrowser({
headless: true,
model: 'openai/gpt-5.6-sol',
selfHeal: true,
})

export const browserAgent = new Agent({
id: 'browser-agent',
name: 'Browser Agent',
instructions: `You can browse the web using natural language.
Use stagehand_act to perform actions like "click the login button".
Use stagehand_extract to get data from pages.`,
model: 'openai/gpt-5.6-sol',
browser,
})

Constructor 參數
「Constructor 參數」的直接連結

headless?:

boolean
= true
是否以 headless 模式執行瀏覽器。

viewport?:

{ width: number; height: number } | 'window'
= { width: 1280, height: 720 }
瀏覽器 viewport 尺寸。window 會符合實際瀏覽器視窗,而且只適用於透過 CDP 連線;本機啟動的瀏覽器會改用預設尺寸。

env?:

'LOCAL' | 'BROWSERBASE'
= 'LOCAL'
執行瀏覽器的環境。雲端執行請使用 'BROWSERBASE'。

apiKey?:

string
Browserbase API key。env 為 'BROWSERBASE' 時必填。

projectId?:

string
Browserbase project ID。env 為 'BROWSERBASE' 時必填。

model?:

string | ModelConfiguration
= 'openai/gpt-5.5'
AI 操作的模型設定。可以是 'openai/gpt-5.5' 等字串,也可以是包含 modelName、apiKey 與 baseURL 的物件。

selfHeal?:

boolean
= true
啟用自我修復 selector。啟用後,初始 selector 失敗時,Stagehand 會使用 AI 尋找 element。

domSettleTimeout?:

number
= 5000
動作完成後等待 DOM 穩定的逾時毫秒數。

verbose?:

0 | 1 | 2
= 1
logging 詳細程度。0 = 靜默,1 = 僅錯誤,2 = 詳細。

systemPrompt?:

string
AI 操作的自訂 system prompt。

cdpUrl?:

string | (() => string | Promise<string>)
用於連線至現有瀏覽器的 CDP WebSocket URL 或 HTTP endpoint。HTTP endpoint 會在內部解析為 WebSocket。

scope?:

'shared' | 'thread'
= 'thread' (or 'shared' when cdpUrl is provided)
瀏覽器 instance 跨 thread 的範圍。

timeout?:

number
= 30000
Stagehand 操作的預設逾時毫秒數。

onLaunch?:

(args: { browser: MastraBrowser }) => void | Promise<void>
瀏覽器準備就緒後呼叫的 callback。

onClose?:

(args: { browser: MastraBrowser }) => void | Promise<void>
瀏覽器關閉前呼叫的 callback。

screencast?:

ScreencastOptions
將瀏覽器 frame 串流至 Studio 的設定。

recording?:

BrowserRecordingOptions
新增瀏覽器錄製 Tool 的 Alpha 選項。提供 outputDir 會將 browser_record 與 browser_record_caption 加入 Tool 集合。也可設定 maxDurationMs、maxWidth 與 maxHeight,作為每次錄製的預設值。

excludeTools?:

StagehandToolName[]
要從瀏覽器 Tool 集合排除的 Tool 名稱。可用於停用模型不支援的特定能力,例如 vision。

Tool
「Tool」的直接連結

StagehandBrowser 提供 7 個 AI 驅動的瀏覽器自動化 Tool。

設定 recording 後,StagehandBrowser 也會加入 Alpha 版的 browser_recordbrowser_record_caption Tool。請參閱瀏覽器錄製(Alpha)

核心 Tool:

Tool說明
stagehand_act使用自然語言 instructions 執行動作
stagehand_extract從頁面擷取結構化資料
stagehand_observe探索頁面上有用的 element
stagehand_navigate前往 URL
stagehand_tabs管理瀏覽器分頁
stagehand_screenshot以 PNG 擷取螢幕截圖(預設為 viewport;設定 fullPage: true 可擷取完整頁面)
stagehand_close關閉瀏覽器

若要排除特定 Tool,請將 excludeTools 傳給 constructor:

const browser = new StagehandBrowser({
excludeTools: ['stagehand_screenshot'],
})

Tool 參考文件
「Tool 參考文件」的直接連結

stagehand_act
「stagehand_act」的直接連結

使用自然語言 instructions 執行動作。AI 會解讀 instructions,並執行適當的瀏覽器動作。

// Tool input
{
"instruction": "click the login button",
"variables": { "username": "john" },
"useVision": true,
"timeout": 30000
}

// With variable substitution
{
"instruction": "type %email% into the email field",
"variables": { "email": "user@example.com" }
}
參數型別說明
instructionstring自然語言 instruction(必填)
variablesRecord<string, string>用於 %variableName% 替換的變數(選填)
useVisionboolean啟用 vision 能力(選填)
timeoutnumber逾時毫秒數(選填)

傳回:

interface ActResult {
success: boolean
message?: string
action?: string
url?: string
}

stagehand_extract
「stagehand_extract」的直接連結

使用自然語言 instructions 從頁面擷取結構化資料。

// Basic extraction
{
"instruction": "extract all product names and prices"
}

// With schema for structured output
{
"instruction": "extract the product information",
"schema": {
"type": "object",
"properties": {
"name": { "type": "string" },
"price": { "type": "number" },
"inStock": { "type": "boolean" }
}
}
}

傳回:

interface ExtractResult<T = unknown> {
success: boolean
data?: T
hint?: string
error?: string
url?: string
}

stagehand_observe
「stagehand_observe」的直接連結

探索頁面上有用的 element。傳回 element 清單,包括 selector 與 description。

// Find specific elements
{
"instruction": "find all buttons related to checkout"
}

// Find all interactive elements
{
"onlyVisible": true
}
參數型別說明
instructionstring自然語言 instruction(選填;省略可尋找全部)
onlyVisibleboolean只包含可見 element(選填)
timeoutnumber逾時毫秒數(選填)

傳回:

interface ObserveResult {
success: boolean
actions: StagehandAction[]
url?: string
}

interface StagehandAction {
selector: string
description: string
method?: string
arguments?: string[]
}

stagehand_navigate
「stagehand_navigate」的直接連結

前往 URL。

// Tool input
{
"url": "https://example.com",
"waitUntil": "domcontentloaded"
}
參數型別說明
urlstring要開啟的 URL(必填)
waitUntil"load" | "domcontentloaded" | "networkidle"何時將導覽視為完成(選填)

stagehand_tabs
「stagehand_tabs」的直接連結

管理瀏覽器分頁。

// List all tabs
{ "action": "list" }

// Open new tab
{ "action": "new", "url": "https://example.com" }

// Switch to tab by index
{ "action": "switch", "index": 0 }

// Close tab by index (or current if omitted)
{ "action": "close", "index": 1 }

stagehand_screenshot
「stagehand_screenshot」的直接連結

將目前頁面擷取為 PNG 螢幕截圖(預設為 viewport;設定 fullPage: true 可擷取完整頁面)。傳回的圖片內容可由具備 vision 能力的模型直接解讀。只需要文字或結構化資料時,請使用 stagehand_observestagehand_extract

// Viewport only (default)
{}

// Full scrollable page
{ "fullPage": true }
參數型別說明
fullPageboolean擷取完整可捲動頁面,而不只是 viewport(選填,預設:false)

stagehand_close
「stagehand_close」的直接連結

關閉瀏覽器並清理資源。

// Tool input (no parameters required)
{}

使用 Browserbase
「使用 Browserbase」的直接連結

透過 Browserbase 在雲端執行 Stagehand:

const browser = new StagehandBrowser({
env: 'BROWSERBASE',
apiKey: process.env.BROWSERBASE_API_KEY,
projectId: process.env.BROWSERBASE_PROJECT_ID,
model: 'openai/gpt-5.6-sol',
})

模型設定
「模型設定」的直接連結

設定 Stagehand 操作所使用的 AI 模型:

// String format: "provider/model"
const browser = new StagehandBrowser({
model: 'openai/gpt-5.6-sol',
})

// Object format for custom configuration
const browser = new StagehandBrowser({
model: {
modelName: 'gpt-5.4',
apiKey: process.env.OPENAI_API_KEY,
baseURL: 'https://api.openai.com/v1',
},
})

AgentBrowser 與 StagehandBrowser 比較
「AgentBrowser 與 StagehandBrowser 比較」的直接連結

面向AgentBrowserStagehandBrowser
方法確定性 ref(@e5自然語言
精確度精確指定 elementAI 解讀
彈性必須先取得 snapshot直接使用 instructions
使用情境可重現的自動化可調適的自動化
速度較快(不需 AI inference)較慢(需要 AI inference)

需要精確且可重現的自動化時,請選擇 AgentBrowser。需要靈活的自然語言互動時,請選擇 StagehandBrowser