-
Notifications
You must be signed in to change notification settings - Fork 1.6k
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 10 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,83 @@ | ||
| import { Stagehand } from "@/dist"; | ||
| import dotenv from "dotenv"; | ||
| import StagehandConfig from "@/stagehand.config"; | ||
| import chalk from "chalk"; | ||
|
|
||
| // Load environment variables | ||
| dotenv.config(); | ||
|
|
||
| async function main() { | ||
| console.log(`\n${chalk.bold("Stagehand 🤘 Native Agent Example")}\n`); | ||
|
|
||
| // Initialize Stagehand | ||
| console.log(`${chalk.cyan("→")} Initializing Stagehand...`); | ||
| const stagehand = new Stagehand({ | ||
| ...StagehandConfig, | ||
| }); | ||
|
|
||
| await stagehand.init(); | ||
| console.log(`${chalk.green("✓")} Stagehand initialized`); | ||
|
|
||
| try { | ||
| const page = stagehand.page; | ||
|
|
||
| console.log(`\n${chalk.magenta.bold("⚡ First Agent Execution")}`); | ||
|
|
||
| const agent = stagehand.agent({ | ||
| instructions: `You are a helpful assistant that can use a web browser. | ||
| You are currently on the following page: ${page.url()}. | ||
| Do not ask follow up questions, the user will trust your judgement.`, | ||
| }); | ||
|
|
||
| console.log(`${chalk.yellow("→")} Navigating to Google...`); | ||
| await stagehand.page.goto("https://www.google.com"); | ||
| console.log(`${chalk.green("✓")} Loaded: ${chalk.dim(page.url())}`); | ||
|
|
||
| // Execute the agent again with a different instruction | ||
| const firstInstruction = | ||
| "Search for openai news on google and extract the name of the first 3 results"; | ||
| console.log( | ||
| `${chalk.cyan("↳")} Instruction: ${chalk.white(firstInstruction)}`, | ||
| ); | ||
|
|
||
| const result1 = await agent.execute(firstInstruction); | ||
|
|
||
| console.log(`${chalk.green("✓")} Execution complete`); | ||
| console.log(`${chalk.yellow("⤷")} Result:`); | ||
| console.log(chalk.white(JSON.stringify(result1, null, 2))); | ||
|
|
||
| console.log(`\n${chalk.magenta.bold("⚡ Second Agent Execution")}`); | ||
|
|
||
| console.log(`\n${chalk.yellow("→")} Navigating to Apple...`); | ||
| await page.goto("https://www.apple.com/shop/buy-mac/macbook-air"); | ||
| console.log(`${chalk.green("✓")} Loaded: ${chalk.dim(page.url())}`); | ||
|
|
||
| const instruction = | ||
| "Add a macbook air to the cart. Choose the most expensive configuration."; | ||
| console.log(`${chalk.cyan("↳")} Instruction: ${chalk.white(instruction)}`); | ||
|
|
||
| const result = await agent.execute({ | ||
| instruction, | ||
| maxSteps: 20, | ||
| }); | ||
|
|
||
| console.log(`${chalk.green("✓")} Execution complete`); | ||
| console.log(`${chalk.yellow("⤷")} Result:`); | ||
| console.log(chalk.white(JSON.stringify(result, null, 2))); | ||
| } catch (error) { | ||
| console.log(`${chalk.red("✗")} Error: ${error}`); | ||
| if (error instanceof Error && error.stack) { | ||
| console.log(chalk.dim(error.stack.split("\n").slice(1).join("\n"))); | ||
| } | ||
| } finally { | ||
| // Close the browser | ||
| console.log(`\n${chalk.yellow("→")} Closing browser...`); | ||
| await stagehand.close(); | ||
| console.log(`${chalk.green("✓")} Browser closed\n`); | ||
| } | ||
| } | ||
|
|
||
| main().catch((error) => { | ||
| console.log(`${chalk.red("✗")} Unhandled error in main function`); | ||
| console.log(chalk.red(error)); | ||
| }); |
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,189 @@ | ||
| import { | ||
| AgentAction, | ||
| AgentExecuteOptions, | ||
| AgentResult, | ||
| ActionExecutionResult, | ||
| } from "@/types/agent"; | ||
| import { LogLine } from "@/types/log"; | ||
| import { OperatorResponse, operatorResponseSchema } from "@/types/operator"; | ||
| import { LLMParsedResponse } from "../inference"; | ||
| import { ChatMessage, LLMClient } from "../llm/LLMClient"; | ||
| import { buildOperatorSystemPrompt } from "../prompt"; | ||
| import { StagehandPage } from "../StagehandPage"; | ||
|
|
||
| export class StagehandOperatorHandler { | ||
| private stagehandPage: StagehandPage; | ||
| private logger: (message: LogLine) => void; | ||
| private llmClient: LLMClient; | ||
| messages: ChatMessage[]; | ||
| private lastActionResult: ActionExecutionResult | null = null; | ||
| private lastMethod: string | null = null; | ||
|
|
||
| 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}):`; | ||
|
|
||
| if (this.lastMethod && this.lastActionResult) { | ||
| const statusMessage = this.lastActionResult.success | ||
| ? "was successful" | ||
| : `failed with error: ${this.lastActionResult.error}`; | ||
|
|
||
| messageText = `Previous action '${this.lastMethod}' ${statusMessage}.\n\n${messageText}`; | ||
|
|
||
| if ( | ||
| this.lastMethod === "extract" && | ||
| this.lastActionResult.success && | ||
| this.lastActionResult.data | ||
| ) { | ||
| messageText = `Previous extraction result: ${JSON.stringify(this.lastActionResult.data, null, 2)}\n\n${messageText}`; | ||
| } | ||
| } | ||
|
|
||
| this.messages.push({ | ||
| role: "user", | ||
| content: [ | ||
| { | ||
| type: "text", | ||
| text: messageText, | ||
| }, | ||
| { | ||
| type: "image_url", | ||
| image_url: { url: `data:image/png;base64,${base64Image}` }, | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. anthropic's format: messages: [
{
"role": "user",
"content": [
{
"type": "image",
"source": {
"type": "base64",
"media_type": image_media_type,
"data": image_data,
},
},
... |
||
| }, | ||
| ], | ||
| }); | ||
| } | ||
|
|
||
| const result = await this.getNextStep(currentStep); | ||
|
|
||
| if (result.method === "close") { | ||
| completed = true; | ||
| } | ||
|
|
||
| actions.push({ | ||
| type: result.method, | ||
| reasoning: result.reasoning, | ||
| taskCompleted: result.taskComplete, | ||
| }); | ||
|
|
||
| currentStep++; | ||
|
|
||
| try { | ||
| const actionResult = await this.executeAction(result); | ||
| this.lastActionResult = { | ||
| success: true, | ||
| data: actionResult, | ||
| }; | ||
| } catch (error) { | ||
| this.lastActionResult = { | ||
| success: false, | ||
| error: error instanceof Error ? error.message : String(error), | ||
| }; | ||
| } | ||
|
|
||
| this.lastMethod = result.method; | ||
| } | ||
|
|
||
| return { | ||
| success: true, | ||
| message: actions[actions.length - 1].reasoning as string, | ||
| 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 executeAction(action: OperatorResponse): Promise<unknown> { | ||
| const { method, parameters } = action; | ||
| const page = this.stagehandPage.page; | ||
|
|
||
| if (method === "close") { | ||
| return; | ||
| } | ||
|
|
||
| switch (method) { | ||
| case "act": | ||
| await page.act({ | ||
| action: parameters, | ||
| slowDomBasedAct: false, | ||
| timeoutMs: 5000, | ||
| }); | ||
| break; | ||
| case "extract": | ||
| return await page.extract(parameters); | ||
| 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.
In a fast follow PR, let's use stagehand.history here