diff --git a/.changeset/curly-rules-build.md b/.changeset/curly-rules-build.md new file mode 100644 index 000000000..96ec06805 --- /dev/null +++ b/.changeset/curly-rules-build.md @@ -0,0 +1,5 @@ +--- +"@browserbasehq/stagehand": minor +--- + +Added support for offloading agent tasks to the API. diff --git a/lib/api.ts b/lib/api.ts index d4506bacb..8ebe6161e 100644 --- a/lib/api.ts +++ b/lib/api.ts @@ -12,11 +12,13 @@ import { GotoOptions } from "../types/playwright"; import { ActOptions, ActResult, + AgentConfig, ExtractOptions, ExtractResult, ObserveOptions, ObserveResult, } from "../types/stagehand"; +import { AgentExecuteOptions, AgentResult } from "."; export class StagehandAPI { private apiKey: string; @@ -112,6 +114,16 @@ export class StagehandAPI { }); } + async agentExecute( + agentConfig: AgentConfig, + executeOptions: AgentExecuteOptions, + ): Promise { + return this.execute({ + method: "agentExecute", + args: { agentConfig, executeOptions }, + }); + } + async end(): Promise { const url = `/sessions/${this.sessionId}/end`; return await this.request(url, { diff --git a/lib/index.ts b/lib/index.ts index c4e6b0ede..b7416adc8 100644 --- a/lib/index.ts +++ b/lib/index.ts @@ -841,6 +841,32 @@ export class Stagehand { throw new Error("Instruction is required for agent execution"); } + if (this.usingAPI) { + if (!this.apiClient) { + throw new Error( + "API client not initialized. Ensure that you have initialized Stagehand via `await stagehand.init()`.", + ); + } + + if (!options.options) { + options.options = {}; + } + + if (options.provider === "anthropic") { + options.options.apiKey = process.env.ANTHROPIC_API_KEY; + } else if (options.provider === "openai") { + options.options.apiKey = process.env.OPENAI_API_KEY; + } + + if (!options.options.apiKey) { + throw new Error( + `API key not found for \`${options.provider}\` provider. Please set the ${options.provider === "anthropic" ? "ANTHROPIC_API_KEY" : "OPENAI_API_KEY"} environment variable or pass an apiKey in the options object.`, + ); + } + + return await this.apiClient.agentExecute(options, executeOptions); + } + return await agentHandler.execute(executeOptions); }, }; diff --git a/types/api.ts b/types/api.ts index 3a66c4913..edcef289f 100644 --- a/types/api.ts +++ b/types/api.ts @@ -8,7 +8,7 @@ export interface StagehandAPIConstructorParams { } export interface ExecuteActionParams { - method: "act" | "extract" | "observe" | "navigate" | "end"; + method: "act" | "extract" | "observe" | "navigate" | "end" | "agentExecute"; args?: unknown; params?: unknown; }