-
Notifications
You must be signed in to change notification settings - Fork 1.3k
operator handler #586
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
kamath
merged 13 commits into
main
from
sarif/stg-182-native-oo-agent-loop-in-addition-to-cua
Mar 18, 2025
Merged
operator handler #586
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
f92b417
operator handler
sameelarif 1e68273
changeset
sameelarif 7503bda
Update young-dots-fry.md
sameelarif 5e20e6e
better task memory & cleaner code
sameelarif 8abee79
provide extraction result in reasoning
sameelarif 799aae7
remove action log
sameelarif dd5cc70
make agent config optional
sameelarif 5904826
increase max steps
sameelarif 44a64b7
update close logic
sameelarif 5266429
add operator example
sameelarif 16ad0f2
made handler messages private
sameelarif 9bd84f9
Merge branch 'main' into sarif/stg-182-native-oo-agent-loop-in-additi…
sameelarif f2acb14
update operator (#596)
kamath File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| "@browserbasehq/stagehand": minor | ||
| --- | ||
|
|
||
| Added native Stagehand agentic loop functionality. This allows you to build agentic workflows with a single prompt without using a computer-use model. To try it out, create a `stagehand.agent` without passing in a provider. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,47 @@ | ||
| import { LogLine, Stagehand } from "@/dist"; | ||
| import dotenv from "dotenv"; | ||
| import StagehandConfig from "@/stagehand.config"; | ||
| import chalk from "chalk"; | ||
|
|
||
| // Load environment variables | ||
| dotenv.config(); | ||
|
|
||
| const INSTRUCTION = | ||
| "Go to Google Japan and interact with it in Japanese. Tell me (in English) an authentic recipe that I can make with ingredients found in American grocery stores."; | ||
|
|
||
| async function main() { | ||
| console.log(`\n${chalk.bold("Stagehand 🤘 Operator Example")}\n`); | ||
|
|
||
| // Initialize Stagehand | ||
| const stagehand = new Stagehand({ | ||
| ...StagehandConfig, | ||
| logger: ({ level, message, timestamp }: LogLine) => { | ||
| console.log({ level, message, timestamp }); | ||
| }, | ||
| }); | ||
|
|
||
| await stagehand.init(); | ||
|
|
||
| try { | ||
| const agent = stagehand.agent(); | ||
|
|
||
| // Execute the agent | ||
| console.log(`${chalk.cyan("↳")} Instruction: ${INSTRUCTION}`); | ||
|
|
||
| const result = await agent.execute({ | ||
| instruction: INSTRUCTION, | ||
| maxSteps: 20, | ||
| }); | ||
|
|
||
| console.log(`${chalk.green("✓")} Execution complete`); | ||
| console.log(`${chalk.yellow("⤷")} Result:`); | ||
| console.log(JSON.stringify(result, null, 2)); | ||
| console.log(chalk.white(result.message)); | ||
| } catch (error) { | ||
| console.log(`${chalk.red("✗")} Error: ${error}`); | ||
| } finally { | ||
| await stagehand.close(); | ||
| } | ||
| } | ||
|
|
||
| main(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,221 @@ | ||
| import { AgentAction, AgentExecuteOptions, AgentResult } from "@/types/agent"; | ||
| import { LogLine } from "@/types/log"; | ||
| import { | ||
| OperatorResponse, | ||
| operatorResponseSchema, | ||
| OperatorSummary, | ||
| operatorSummarySchema, | ||
| } from "@/types/operator"; | ||
| import { LLMParsedResponse } from "../inference"; | ||
| import { ChatMessage, LLMClient } from "../llm/LLMClient"; | ||
| import { buildOperatorSystemPrompt } from "../prompt"; | ||
| import { StagehandPage } from "../StagehandPage"; | ||
| import { ObserveResult } from "@/types/stagehand"; | ||
|
|
||
| export class StagehandOperatorHandler { | ||
| private stagehandPage: StagehandPage; | ||
| private logger: (message: LogLine) => void; | ||
| private llmClient: LLMClient; | ||
| private messages: ChatMessage[]; | ||
|
|
||
| constructor( | ||
| stagehandPage: StagehandPage, | ||
| logger: (message: LogLine) => void, | ||
| llmClient: LLMClient, | ||
| ) { | ||
| this.stagehandPage = stagehandPage; | ||
| this.logger = logger; | ||
| this.llmClient = llmClient; | ||
| } | ||
|
|
||
| public async execute( | ||
| instructionOrOptions: string | AgentExecuteOptions, | ||
| ): Promise<AgentResult> { | ||
| const options = | ||
| typeof instructionOrOptions === "string" | ||
| ? { instruction: instructionOrOptions } | ||
| : instructionOrOptions; | ||
|
|
||
| this.messages = [buildOperatorSystemPrompt(options.instruction)]; | ||
| let completed = false; | ||
| let currentStep = 0; | ||
| const maxSteps = options.maxSteps || 10; | ||
| const actions: AgentAction[] = []; | ||
|
|
||
| while (!completed && currentStep < maxSteps) { | ||
| const url = this.stagehandPage.page.url(); | ||
|
|
||
| if (!url || url === "about:blank") { | ||
| this.messages.push({ | ||
| role: "user", | ||
| content: [ | ||
| { | ||
| type: "text", | ||
| text: "No page is currently loaded. The first step should be a 'goto' action to navigate to a URL.", | ||
| }, | ||
| ], | ||
| }); | ||
| } else { | ||
| const screenshot = await this.stagehandPage.page.screenshot({ | ||
| type: "png", | ||
| fullPage: false, | ||
| }); | ||
|
|
||
| const base64Image = screenshot.toString("base64"); | ||
|
|
||
| let messageText = `Here is a screenshot of the current page (URL: ${url}):`; | ||
|
|
||
| messageText = `Previous actions were: ${actions | ||
| .map((action) => { | ||
| let result: string = ""; | ||
| if (action.type === "act") { | ||
| const args = action.playwrightArguments as ObserveResult; | ||
| result = `Performed a "${args.method}" action ${args.arguments.length > 0 ? `with arguments: ${args.arguments.map((arg) => `"${arg}"`).join(", ")}` : ""} on "${args.description}"`; | ||
| } else if (action.type === "extract") { | ||
| result = `Extracted data: ${action.extractionResult}`; | ||
| } | ||
| return `[${action.type}] ${action.reasoning}. Result: ${result}`; | ||
| }) | ||
| .join("\n")}\n\n${messageText}`; | ||
|
|
||
| this.messages.push({ | ||
| role: "user", | ||
| content: [ | ||
| { | ||
| type: "text", | ||
| text: messageText, | ||
| }, | ||
| { | ||
| type: "image_url", | ||
| image_url: { url: `data:image/png;base64,${base64Image}` }, | ||
| }, | ||
| ], | ||
| }); | ||
| } | ||
|
|
||
| const result = await this.getNextStep(currentStep); | ||
|
|
||
| if (result.method === "close") { | ||
| completed = true; | ||
| } | ||
|
|
||
| let playwrightArguments: ObserveResult | undefined; | ||
| if (result.method === "act") { | ||
| [playwrightArguments] = await this.stagehandPage.page.observe( | ||
| result.parameters, | ||
| ); | ||
| } | ||
| let extractionResult: unknown | undefined; | ||
| if (result.method === "extract") { | ||
| extractionResult = await this.stagehandPage.page.extract( | ||
| result.parameters, | ||
| ); | ||
| } | ||
|
|
||
| await this.executeAction(result, playwrightArguments, extractionResult); | ||
|
|
||
| actions.push({ | ||
| type: result.method, | ||
| reasoning: result.reasoning, | ||
| taskCompleted: result.taskComplete, | ||
| parameters: result.parameters, | ||
| playwrightArguments, | ||
| extractionResult, | ||
| }); | ||
|
|
||
| currentStep++; | ||
| } | ||
|
|
||
| return { | ||
| success: true, | ||
| message: await this.getSummary(options.instruction), | ||
| actions, | ||
| completed: actions[actions.length - 1].taskCompleted as boolean, | ||
| }; | ||
| } | ||
|
|
||
| private async getNextStep(currentStep: number): Promise<OperatorResponse> { | ||
| const { data: response } = | ||
| (await this.llmClient.createChatCompletion<OperatorResponse>({ | ||
| options: { | ||
| messages: this.messages, | ||
| response_model: { | ||
| name: "operatorResponseSchema", | ||
| schema: operatorResponseSchema, | ||
| }, | ||
| requestId: `operator-step-${currentStep}`, | ||
| }, | ||
| logger: this.logger, | ||
| })) as LLMParsedResponse<OperatorResponse>; | ||
|
|
||
| return response; | ||
| } | ||
|
|
||
| private async getSummary(goal: string): Promise<string> { | ||
| const { data: response } = | ||
| (await this.llmClient.createChatCompletion<OperatorSummary>({ | ||
| options: { | ||
| messages: [ | ||
| ...this.messages, | ||
| { | ||
| role: "user", | ||
| content: [ | ||
| { | ||
| type: "text", | ||
| text: `Now use the steps taken to answer the original instruction of ${goal}.`, | ||
| }, | ||
| ], | ||
| }, | ||
| ], | ||
| response_model: { | ||
| name: "operatorSummarySchema", | ||
| schema: operatorSummarySchema, | ||
| }, | ||
| requestId: "operator-summary", | ||
| }, | ||
| logger: this.logger, | ||
| })) as LLMParsedResponse<OperatorSummary>; | ||
|
|
||
| return response.answer; | ||
| } | ||
| private async executeAction( | ||
| action: OperatorResponse, | ||
| playwrightArguments?: ObserveResult, | ||
| extractionResult?: unknown, | ||
| ): Promise<unknown> { | ||
| const { method, parameters } = action; | ||
| const page = this.stagehandPage.page; | ||
|
|
||
| if (method === "close") { | ||
| return; | ||
| } | ||
|
|
||
| switch (method) { | ||
| case "act": | ||
| if (!playwrightArguments) { | ||
| throw new Error("No playwright arguments provided"); | ||
| } | ||
| await page.act(playwrightArguments); | ||
| break; | ||
| case "extract": | ||
| if (!extractionResult) { | ||
| throw new Error("No extraction result provided"); | ||
| } | ||
| return extractionResult; | ||
| case "goto": | ||
| await page.goto(parameters, { waitUntil: "load" }); | ||
| break; | ||
| case "wait": | ||
| await page.waitForTimeout(parseInt(parameters)); | ||
| break; | ||
| case "navback": | ||
| await page.goBack(); | ||
| break; | ||
| case "refresh": | ||
| await page.reload(); | ||
| break; | ||
| default: | ||
| throw new Error(`Unknown action: ${method}`); | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
anthropic's format: