await page.goto("https://github.com/browserbase/stagehand");// Create a Computer Use agent with just one line of code!const agent = stagehand.agent({ provider: "openai", model: "computer-use-preview"});// Use the agent to execute a taskconst result = await agent.execute("Extract the top contributor's username");console.log(result);
await stagehand.page.goto("https://github.com/browserbase/stagehand");// Open Operator will use the default LLM from Stagehand configconst operator = stagehand.agent();const { message, actions } = await operator.execute( "Extract the top contributor's username");console.log(message);
import { AgentAction, AgentResult } from "@browserbasehq/stagehand";import { exec } from "child_process";import fs from "fs/promises";export async function replay(result: AgentResult) { const history = result.actions; const replay = history .map((action: AgentAction) => { switch (action.type) { case "act": if (!action.playwrightArguments) { throw new Error("No playwright arguments provided"); } return `await page.act(${JSON.stringify( action.playwrightArguments )})`; case "extract": return `await page.extract("${action.parameters}")`; case "goto": return `await page.goto("${action.parameters}")`; case "wait": return `await page.waitForTimeout(${parseInt( action.parameters as string )})`; case "navback": return `await page.goBack()`; case "refresh": return `await page.reload()`; case "close": return `await stagehand.close()`; default: return `await stagehand.oops()`; } }) .join("\n"); console.log("回放操作:"); const boilerplate = `import { Page, BrowserContext, Stagehand } from "@browserbasehq/stagehand";export async function main(stagehand: Stagehand) { const page = stagehand.page ${replay}} `; await fs.writeFile("replay.ts", boilerplate); // 使用prettier格式化回放文件 await new Promise((resolve, reject) => { exec( "npx prettier --write replay.ts", (error: any, stdout: any, stderr: any) => { if (error) { console.error(`格式化replay.ts时出错: ${error}`); reject(error); return; } resolve(stdout); } ); });}
以下是类似指令 "获取英伟达(NVDA)的股价" 的回放输出:
replay.ts
import { Page, BrowserContext, Stagehand } from "@browserbasehq/stagehand";export async function main({ page, context, stagehand,}: { page: Page; // Playwright Page with act, extract, and observe methods context: BrowserContext; // Playwright BrowserContext stagehand: Stagehand; // Stagehand instance}) { await page.goto("https://www.google.com"); // Replay will default to Playwright first to avoid unnecessary LLM calls! // If the Playwright action fails, Stagehand AI will take over and self-heal await page.act({ description: "The search combobox where users can type their queries.", method: "fill", arguments: ["NVDA stock price"], selector: "xpath=/html/body[1]/div[1]/div[3]/form[1]/div[1]/div[1]/div[1]/div[1]/div[2]/textarea[1]", }); await page.extract( "the displayed NVDA stock price in the search suggestions", ); await stagehand.close();}