> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-HK/llms.txt # StagehandBrowser 類別 `StagehandBrowser` 類別透過 [Stagehand](https://github.com/browserbase/stagehand) 提供由 AI 驅動的瀏覽器自動化功能。它使用自然語言指令進行互動,而非元素參照。 如果你希望由 AI 解讀自然語言並執行瀏覽器操作,請使用 `StagehandBrowser`。如要透過元素參照進行確定性自動化,請參閱 [`AgentBrowser`](https://mastra.zisheng.pro/zh-HK/reference/browser/agent-browser)。 ## 使用範例 ```typescript 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, }) ``` ## 建構函式參數 **headless** (`boolean`): 是否以無頭模式執行瀏覽器。 (Default: `true`) **viewport** (`{ width: number; height: number } | 'window'`): 瀏覽器視窗區域的尺寸。'window' 會配合實際瀏覽器視窗,而且只適用於透過 CDP 連線的情況;在本機啟動的瀏覽器則會改用預設尺寸。 (Default: `{ width: 1280, height: 720 }`) **env** (`'LOCAL' | 'BROWSERBASE'`): 執行瀏覽器的環境。使用 'BROWSERBASE' 在雲端執行。 (Default: `'LOCAL'`) **apiKey** (`string`): Browserbase API 金鑰。當 env 為 'BROWSERBASE' 時必須提供。 **projectId** (`string`): Browserbase 項目 ID。當 env 為 'BROWSERBASE' 時必須提供。 **model** (`string | ModelConfiguration`): AI 操作的模型設定。可以是類似 'openai/gpt-5.5' 的字串,亦可以是包含 modelName、apiKey 及 baseURL 的物件。 (Default: `'openai/gpt-5.5'`) **selfHeal** (`boolean`): 啟用可自動修復的選擇器。啟用後,即使最初的選擇器失效,Stagehand 亦會使用 AI 尋找元素。 (Default: `true`) **domSettleTimeout** (`number`): 操作後等待 DOM 穩定的逾時時間(毫秒)。 (Default: `5000`) **verbose** (`0 | 1 | 2`): 記錄詳細程度。0 = 靜默、1 = 只記錄錯誤、2 = 詳細記錄。 (Default: `1`) **systemPrompt** (`string`): AI 操作所使用的自訂系統提示。 **cdpUrl** (`string | (() => string | Promise)`): 用來連接現有瀏覽器的 CDP WebSocket URL 或 HTTP 端點。HTTP 端點會在內部解析為 WebSocket。 **scope** (`'shared' | 'thread'`): 瀏覽器實例在各執行緒之間的作用範圍。 (Default: `'thread' (or 'shared' when cdpUrl is provided)`) **timeout** (`number`): Stagehand 操作的預設逾時時間(毫秒)。 (Default: `30000`) **onLaunch** (`(args: { browser: MastraBrowser }) => void | Promise`): 瀏覽器準備就緒後呼叫的回呼函式。 **onClose** (`(args: { browser: MastraBrowser }) => void | Promise`): 瀏覽器關閉前呼叫的回呼函式。 **screencast** (`ScreencastOptions`): 將瀏覽器影格串流至 Studio 的設定。 **recording** (`BrowserRecordingOptions`): 加入瀏覽器錄影 Tool 的 alpha 選項。提供 outputDir,即可將 browser\_record 及 browser\_record\_caption 加入 Tool 集。你亦可設定 maxDurationMs、maxWidth 及 maxHeight,作為每段錄影的預設值。 **excludeTools** (`StagehandToolName[]`): 要從瀏覽器 Tool 集排除的 Tool 名稱。對於不支援視覺等特定功能的模型,可使用此選項停用個別 Tool。 ## Tools `StagehandBrowser` 提供 7 個由 AI 驅動的瀏覽器自動化 Tool。 設定 `recording` 後,`StagehandBrowser` 亦會加入 alpha 版 `browser_record` 及 `browser_record_caption` Tool。詳情請參閱[瀏覽器錄影(alpha)](https://mastra.zisheng.pro/zh-HK/docs/browser/recording)。 核心 Tool: | Tool | 說明 | | ---------------------- | -------------------------------------------------- | | `stagehand_act` | 使用自然語言指令執行操作 | | `stagehand_extract` | 從頁面擷取結構化資料 | | `stagehand_observe` | 探索頁面上的實用元素 | | `stagehand_navigate` | 前往 URL | | `stagehand_tabs` | 管理瀏覽器分頁 | | `stagehand_screenshot` | 擷取 PNG 螢幕截圖(預設只擷取視窗區域;設定 `fullPage: true` 可擷取整個頁面) | | `stagehand_close` | 關閉瀏覽器 | 如要排除特定 Tool,請在建構函式中傳入 `excludeTools`: ```typescript const browser = new StagehandBrowser({ excludeTools: ['stagehand_screenshot'], }) ``` ## Tool 參考 ### `stagehand_act` 使用自然語言指令執行操作。AI 會解讀你的指令,並執行適當的瀏覽器操作。 ```text // 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" } } ``` | 參數 | 類型 | 說明 | | ------------- | ------------------------ | --------------------------- | | `instruction` | `string` | 自然語言指令(必須) | | `variables` | `Record` | 用於替換 %variableName% 的變數(選填) | | `useVision` | `boolean` | 啟用視覺功能(選填) | | `timeout` | `number` | 逾時時間(毫秒,選填) | **傳回:** ```typescript interface ActResult { success: boolean message?: string action?: string url?: string } ``` ### `stagehand_extract` 使用自然語言指令從頁面擷取結構化資料。 ```text // 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" } } } } ``` **傳回:** ```typescript interface ExtractResult { success: boolean data?: T hint?: string error?: string url?: string } ``` ### `stagehand_observe` 探索頁面上的實用元素。傳回元素清單,當中包括各元素的選擇器及說明。 ```text // Find specific elements { "instruction": "find all buttons related to checkout" } // Find all interactive elements { "onlyVisible": true } ``` | 參數 | 類型 | 說明 | | ------------- | --------- | -------------------- | | `instruction` | `string` | 自然語言指令(選填;省略即尋找所有元素) | | `onlyVisible` | `boolean` | 只包括可見元素(選填) | | `timeout` | `number` | 逾時時間(毫秒,選填) | **傳回:** ```typescript interface ObserveResult { success: boolean actions: StagehandAction[] url?: string } interface StagehandAction { selector: string description: string method?: string arguments?: string[] } ``` ### `stagehand_navigate` 前往 URL。 ```text // Tool input { "url": "https://example.com", "waitUntil": "domcontentloaded" } ``` | 參數 | 類型 | 說明 | | ----------- | ----------------------------------------------- | ------------- | | `url` | `string` | 要開啟的 URL(必須) | | `waitUntil` | `"load" \| "domcontentloaded" \| "networkidle"` | 判定導覽完成的時機(選填) | ### `stagehand_tabs` 管理瀏覽器分頁。 ```text // 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` 將目前頁面擷取為 PNG 螢幕截圖(預設只擷取視窗區域;設定 `fullPage: true` 可擷取整個頁面)。此 Tool 會傳回具備視覺功能的模型可直接解讀的圖像內容。如果你只需要文字或結構化資料,請使用 `stagehand_observe` 或 `stagehand_extract`。 ```text // Viewport only (default) // Full scrollable page { "fullPage": true } ``` | 參數 | 類型 | 說明 | | ---------- | --------- | --------------------------------- | | `fullPage` | `boolean` | 擷取整個可捲動頁面,而非只擷取視窗區域(選填,預設值:false) | ### `stagehand_close` 關閉瀏覽器並清理資源。 ```text // Tool input (no parameters required) ``` ## 使用 Browserbase 使用 Browserbase 在雲端執行 Stagehand: ```typescript 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 模型: ```typescript // 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 | | -------- | ------------- | ---------------- | | **方式** | 確定性參照(`@e5`) | 自然語言 | | **精準度** | 精確指定元素 | 由 AI 解讀 | | **靈活性** | 必須先建立快照 | 直接使用指令 | | **使用情境** | 可重現的自動化 | 適應性自動化 | | **速度** | 較快(不需要 AI 推論) | 較慢(需要 AI 推論) | 如需精確、可重現的自動化,請選擇 `AgentBrowser`。如需靈活的自然語言互動,請選擇 `StagehandBrowser`。 ## 相關內容 - [MastraBrowser](https://mastra.zisheng.pro/zh-HK/reference/browser/mastra-browser):基礎類別參考 - [AgentBrowser](https://mastra.zisheng.pro/zh-HK/reference/browser/agent-browser):確定性替代方案 - [瀏覽器概覽](https://mastra.zisheng.pro/zh-HK/docs/browser/overview):概念指南 - [Stagehand 指南](https://mastra.zisheng.pro/zh-HK/docs/browser/stagehand):使用指南