|
| 1 | +import { tool } from "ai"; |
| 2 | +import { z } from "zod/v3"; |
| 3 | +import { StagehandPage } from "../../StagehandPage"; |
| 4 | + |
| 5 | +export const createActTool = ( |
| 6 | + stagehandPage: StagehandPage, |
| 7 | + executionModel?: string, |
| 8 | +) => |
| 9 | + tool({ |
| 10 | + description: "Perform an action on the page (click, type)", |
| 11 | + parameters: z.object({ |
| 12 | + action: z.string() |
| 13 | + .describe(`Describe what to click, or type within in a short, specific phrase that mentions the element type. |
| 14 | + Examples: |
| 15 | + - "click the Login button" |
| 16 | + - "click the language dropdown" |
| 17 | + - type "John" into the first name input |
| 18 | + - type "Doe" into the last name input`), |
| 19 | + }), |
| 20 | + execute: async ({ action }) => { |
| 21 | + try { |
| 22 | + let result; |
| 23 | + if (executionModel) { |
| 24 | + result = await stagehandPage.page.act({ |
| 25 | + action, |
| 26 | + modelName: executionModel, |
| 27 | + }); |
| 28 | + } else { |
| 29 | + result = await stagehandPage.page.act(action); |
| 30 | + } |
| 31 | + const isIframeAction = result.action === "an iframe"; |
| 32 | + |
| 33 | + if (isIframeAction) { |
| 34 | + const fallback = await stagehandPage.page.act( |
| 35 | + executionModel |
| 36 | + ? { action, modelName: executionModel, iframes: true } |
| 37 | + : { action, iframes: true }, |
| 38 | + ); |
| 39 | + return { |
| 40 | + success: fallback.success, |
| 41 | + action: fallback.action, |
| 42 | + isIframe: true, |
| 43 | + }; |
| 44 | + } |
| 45 | + |
| 46 | + return { |
| 47 | + success: result.success, |
| 48 | + action: result.action, |
| 49 | + isIframe: false, |
| 50 | + }; |
| 51 | + } catch (error) { |
| 52 | + return { success: false, error: error.message }; |
| 53 | + } |
| 54 | + }, |
| 55 | + }); |
0 commit comments