|
| 1 | +import { AgentAction, AgentExecuteOptions, AgentResult } from "@/types/agent"; |
| 2 | +import { LogLine } from "@/types/log"; |
| 3 | +import { |
| 4 | + OperatorResponse, |
| 5 | + operatorResponseSchema, |
| 6 | + OperatorSummary, |
| 7 | + operatorSummarySchema, |
| 8 | +} from "@/types/operator"; |
| 9 | +import { LLMParsedResponse } from "../inference"; |
| 10 | +import { ChatMessage, LLMClient } from "../llm/LLMClient"; |
| 11 | +import { buildOperatorSystemPrompt } from "../prompt"; |
| 12 | +import { StagehandPage } from "../StagehandPage"; |
| 13 | +import { ObserveResult } from "@/types/stagehand"; |
| 14 | + |
| 15 | +export class StagehandOperatorHandler { |
| 16 | + private stagehandPage: StagehandPage; |
| 17 | + private logger: (message: LogLine) => void; |
| 18 | + private llmClient: LLMClient; |
| 19 | + private messages: ChatMessage[]; |
| 20 | + |
| 21 | + constructor( |
| 22 | + stagehandPage: StagehandPage, |
| 23 | + logger: (message: LogLine) => void, |
| 24 | + llmClient: LLMClient, |
| 25 | + ) { |
| 26 | + this.stagehandPage = stagehandPage; |
| 27 | + this.logger = logger; |
| 28 | + this.llmClient = llmClient; |
| 29 | + } |
| 30 | + |
| 31 | + public async execute( |
| 32 | + instructionOrOptions: string | AgentExecuteOptions, |
| 33 | + ): Promise<AgentResult> { |
| 34 | + const options = |
| 35 | + typeof instructionOrOptions === "string" |
| 36 | + ? { instruction: instructionOrOptions } |
| 37 | + : instructionOrOptions; |
| 38 | + |
| 39 | + this.messages = [buildOperatorSystemPrompt(options.instruction)]; |
| 40 | + let completed = false; |
| 41 | + let currentStep = 0; |
| 42 | + const maxSteps = options.maxSteps || 10; |
| 43 | + const actions: AgentAction[] = []; |
| 44 | + |
| 45 | + while (!completed && currentStep < maxSteps) { |
| 46 | + const url = this.stagehandPage.page.url(); |
| 47 | + |
| 48 | + if (!url || url === "about:blank") { |
| 49 | + this.messages.push({ |
| 50 | + role: "user", |
| 51 | + content: [ |
| 52 | + { |
| 53 | + type: "text", |
| 54 | + text: "No page is currently loaded. The first step should be a 'goto' action to navigate to a URL.", |
| 55 | + }, |
| 56 | + ], |
| 57 | + }); |
| 58 | + } else { |
| 59 | + const screenshot = await this.stagehandPage.page.screenshot({ |
| 60 | + type: "png", |
| 61 | + fullPage: false, |
| 62 | + }); |
| 63 | + |
| 64 | + const base64Image = screenshot.toString("base64"); |
| 65 | + |
| 66 | + let messageText = `Here is a screenshot of the current page (URL: ${url}):`; |
| 67 | + |
| 68 | + messageText = `Previous actions were: ${actions |
| 69 | + .map((action) => { |
| 70 | + let result: string = ""; |
| 71 | + if (action.type === "act") { |
| 72 | + const args = action.playwrightArguments as ObserveResult; |
| 73 | + result = `Performed a "${args.method}" action ${args.arguments.length > 0 ? `with arguments: ${args.arguments.map((arg) => `"${arg}"`).join(", ")}` : ""} on "${args.description}"`; |
| 74 | + } else if (action.type === "extract") { |
| 75 | + result = `Extracted data: ${action.extractionResult}`; |
| 76 | + } |
| 77 | + return `[${action.type}] ${action.reasoning}. Result: ${result}`; |
| 78 | + }) |
| 79 | + .join("\n")}\n\n${messageText}`; |
| 80 | + |
| 81 | + this.messages.push({ |
| 82 | + role: "user", |
| 83 | + content: [ |
| 84 | + { |
| 85 | + type: "text", |
| 86 | + text: messageText, |
| 87 | + }, |
| 88 | + { |
| 89 | + type: "image_url", |
| 90 | + image_url: { url: `data:image/png;base64,${base64Image}` }, |
| 91 | + }, |
| 92 | + ], |
| 93 | + }); |
| 94 | + } |
| 95 | + |
| 96 | + const result = await this.getNextStep(currentStep); |
| 97 | + |
| 98 | + if (result.method === "close") { |
| 99 | + completed = true; |
| 100 | + } |
| 101 | + |
| 102 | + let playwrightArguments: ObserveResult | undefined; |
| 103 | + if (result.method === "act") { |
| 104 | + [playwrightArguments] = await this.stagehandPage.page.observe( |
| 105 | + result.parameters, |
| 106 | + ); |
| 107 | + } |
| 108 | + let extractionResult: unknown | undefined; |
| 109 | + if (result.method === "extract") { |
| 110 | + extractionResult = await this.stagehandPage.page.extract( |
| 111 | + result.parameters, |
| 112 | + ); |
| 113 | + } |
| 114 | + |
| 115 | + await this.executeAction(result, playwrightArguments, extractionResult); |
| 116 | + |
| 117 | + actions.push({ |
| 118 | + type: result.method, |
| 119 | + reasoning: result.reasoning, |
| 120 | + taskCompleted: result.taskComplete, |
| 121 | + parameters: result.parameters, |
| 122 | + playwrightArguments, |
| 123 | + extractionResult, |
| 124 | + }); |
| 125 | + |
| 126 | + currentStep++; |
| 127 | + } |
| 128 | + |
| 129 | + return { |
| 130 | + success: true, |
| 131 | + message: await this.getSummary(options.instruction), |
| 132 | + actions, |
| 133 | + completed: actions[actions.length - 1].taskCompleted as boolean, |
| 134 | + }; |
| 135 | + } |
| 136 | + |
| 137 | + private async getNextStep(currentStep: number): Promise<OperatorResponse> { |
| 138 | + const { data: response } = |
| 139 | + (await this.llmClient.createChatCompletion<OperatorResponse>({ |
| 140 | + options: { |
| 141 | + messages: this.messages, |
| 142 | + response_model: { |
| 143 | + name: "operatorResponseSchema", |
| 144 | + schema: operatorResponseSchema, |
| 145 | + }, |
| 146 | + requestId: `operator-step-${currentStep}`, |
| 147 | + }, |
| 148 | + logger: this.logger, |
| 149 | + })) as LLMParsedResponse<OperatorResponse>; |
| 150 | + |
| 151 | + return response; |
| 152 | + } |
| 153 | + |
| 154 | + private async getSummary(goal: string): Promise<string> { |
| 155 | + const { data: response } = |
| 156 | + (await this.llmClient.createChatCompletion<OperatorSummary>({ |
| 157 | + options: { |
| 158 | + messages: [ |
| 159 | + ...this.messages, |
| 160 | + { |
| 161 | + role: "user", |
| 162 | + content: [ |
| 163 | + { |
| 164 | + type: "text", |
| 165 | + text: `Now use the steps taken to answer the original instruction of ${goal}.`, |
| 166 | + }, |
| 167 | + ], |
| 168 | + }, |
| 169 | + ], |
| 170 | + response_model: { |
| 171 | + name: "operatorSummarySchema", |
| 172 | + schema: operatorSummarySchema, |
| 173 | + }, |
| 174 | + requestId: "operator-summary", |
| 175 | + }, |
| 176 | + logger: this.logger, |
| 177 | + })) as LLMParsedResponse<OperatorSummary>; |
| 178 | + |
| 179 | + return response.answer; |
| 180 | + } |
| 181 | + private async executeAction( |
| 182 | + action: OperatorResponse, |
| 183 | + playwrightArguments?: ObserveResult, |
| 184 | + extractionResult?: unknown, |
| 185 | + ): Promise<unknown> { |
| 186 | + const { method, parameters } = action; |
| 187 | + const page = this.stagehandPage.page; |
| 188 | + |
| 189 | + if (method === "close") { |
| 190 | + return; |
| 191 | + } |
| 192 | + |
| 193 | + switch (method) { |
| 194 | + case "act": |
| 195 | + if (!playwrightArguments) { |
| 196 | + throw new Error("No playwright arguments provided"); |
| 197 | + } |
| 198 | + await page.act(playwrightArguments); |
| 199 | + break; |
| 200 | + case "extract": |
| 201 | + if (!extractionResult) { |
| 202 | + throw new Error("No extraction result provided"); |
| 203 | + } |
| 204 | + return extractionResult; |
| 205 | + case "goto": |
| 206 | + await page.goto(parameters, { waitUntil: "load" }); |
| 207 | + break; |
| 208 | + case "wait": |
| 209 | + await page.waitForTimeout(parseInt(parameters)); |
| 210 | + break; |
| 211 | + case "navback": |
| 212 | + await page.goBack(); |
| 213 | + break; |
| 214 | + case "refresh": |
| 215 | + await page.reload(); |
| 216 | + break; |
| 217 | + default: |
| 218 | + throw new Error(`Unknown action: ${method}`); |
| 219 | + } |
| 220 | + } |
| 221 | +} |
0 commit comments