Stagehand
@mastra/stagehand 依賴套件使用 Browserbase 的 Stagehand SDK 提供瀏覽器自動化功能。Stagehand 運用 AI 理解頁面內容並找出元素,讓你可以使用自然語言描述,毋須明確指定選擇器。
何時使用 Stagehand何時使用 Stagehand 的直接連結
如有以下需要,可使用 Stagehand:
- 以自然語言定位元素(「選取登入按鈕」)
- 從頁面擷取 AI 驅動的資料
- 原生整合 Browserbase 雲端服務
- 為常用操作提供更簡單的 Tool 介面
快速開始快速開始 的直接連結
安裝依賴套件:
- npm
- pnpm
- Yarn
- Bun
npm install @mastra/stagehand
pnpm add @mastra/stagehand
yarn add @mastra/stagehand
bun add @mastra/stagehand
建立瀏覽器實例,並將它指派給 Agent:
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 時,該 Tool 可接受以自然語言描述的操作:
- 「按下 Sign In 按鈕」
- 「在電郵欄位輸入
'[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 時,該 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 時,該 Tool 會擷取目前頁面的 PNG 圖像,並以圖像內容形式傳回,讓支援視覺功能的模型可以直接理解。
如需以視覺方式檢查頁面,例如評估圖像、版面配置或顏色,請使用屏幕截圖。如要處理文字或結構化資料,則應使用 stagehand_extract 或 stagehand_observe。
const browser = new StagehandBrowser({
headless: false,
model: 'openai/gpt-5.6-sol',
})
如要為不支援視覺功能的模型停用屏幕截圖 Tool,請使用 excludeTools:
const browser = new StagehandBrowser({
headless: false,
model: 'openai/gpt-5.6-sol',
excludeTools: ['stagehand_screenshot'],
})
BrowserbaseBrowserbase 的直接連結
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_record 及 browser_record_caption 加入 Agent 的 Tool 集合。詳情請參閱瀏覽器錄製(alpha)。