跳至主要內容

Stagehand

@mastra/stagehand 套件使用 Browserbase 的 Stagehand SDK 提供瀏覽器自動化。Stagehand 使用 AI 理解頁面脈絡並定位元素,因此可以使用自然語言描述,不必明確指定選擇器。

適合使用 Stagehand 的時機
「適合使用 Stagehand 的時機」的直接連結

在需要以下功能時使用 Stagehand:

  • 以自然語言定位元素(「選取登入按鈕」)
  • 使用 AI 從頁面擷取資料
  • 原生 Browserbase 雲端整合
  • 適用常見操作的簡易 Tool 介面

快速開始
「快速開始」的直接連結

安裝套件:

npm install @mastra/stagehand

建立瀏覽器執行個體,並將其指派給 Agent:

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

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

export const stagehandAgent = new Agent({
id: 'stagehand-agent',
name: 'Stagehand Agent',
model: 'openai/gpt-5.6-sol',
browser,
instructions: `You are a web automation assistant.

Use stagehand tools to interact with pages:
- stagehand_navigate to go to URLs
- stagehand_act to perform actions described in natural language
- stagehand_extract to get structured data from the page
- stagehand_observe to find available actions on the page
- stagehand_screenshot to visually inspect the page`,
})

自然語言操作
「自然語言操作」的直接連結

Agent 使用 stagehand_act Tool 時,可以用自然語言描述操作:

  • 「按下登入按鈕」
  • 「在電子郵件欄位中輸入 '[user@example.com](mailto:user@example.com)'
  • 「從國家下拉式選單中選取『United States』」

Stagehand 的 AI 會解讀操作,並在頁面中找到適當的元素。

資料擷取
「資料擷取」的直接連結

Agent 使用 stagehand_extract Tool 時,可以從頁面擷取結構化資料。

指示範例:「擷取產品名稱、價格和供貨狀態」

Tool 會根據頁面內容回傳結構化資料:

{
"name": "Widget Pro",
"price": "$29.99",
"availability": "In Stock"
}

觀察可用操作
「觀察可用操作」的直接連結

Agent 使用 stagehand_observe Tool 時,它會分析目前頁面並回傳可執行的操作。

指示範例:「我可以在這個登入表單上執行哪些操作?」

回傳可用操作的清單:

[
{ "action": "Press 'Sign In' button", "element": "button" },
{ "action": "Type in 'Email' field", "element": "input" },
{ "action": "Open 'Forgot Password' link", "element": "a" }
]

螢幕截圖
「螢幕截圖」的直接連結

當 Agent 使用 stagehand_screenshot Tool 時,它會擷取目前頁面的 PNG 圖片,並以支援視覺功能的模型可直接解讀的圖片內容回傳。

需要以視覺方式檢查頁面時(例如評估圖片、版面或色彩),請使用螢幕截圖。若要取得文字或結構化資料,請改用 stagehand_extractstagehand_observe

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

若模型不支援視覺功能,可使用 excludeTools 停用螢幕截圖 Tool:

const browser = new StagehandBrowser({
headless: false,
model: 'openai/gpt-5.6-sol',
excludeTools: ['stagehand_screenshot'],
})

Browserbase
「Browserbase」的直接連結

Stagehand 原生整合 Browserbase 雲端瀏覽器基礎架構:

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

所有設定選項請參閱 StagehandBrowser 參考文件

錄製
「錄製」的直接連結

Stagehand 可選擇啟用 alpha 階段的瀏覽器錄製 Tool:

const browser = new StagehandBrowser({
headless: false,
model: 'openai/gpt-5.6-sol',
recording: {
outputDir: './browser-recordings',
},
})

這會將 browser_recordbrowser_record_caption 加入 Agent 的 Tool 集合。詳情請參閱瀏覽器錄製(alpha)